1

2# -*- coding: utf-8 -*-

3

4 u'''Mutable, immutable and caching/memoizing properties and

5 deprecation decorators.

6

7 To enable C{DeprecationWarning}s from C{PyGeodesy}, set env var

8 C{PYGEODESY_WARNINGS} to a non-empty string I{AND} run C{python}

9 with command line option C{-X dev} or with one of the C{-W}

10 choices, see callable L{DeprecationWarnings} below.

11'''

12

13# from pygeodesy.basics import isclass # _MODS

14 from pygeodesy.errors import _AssertionError, _AttributeError, \

15 _xkwds, _xkwds_get

16 from pygeodesy.interns import MISSING, NN, _an_, _COMMASPACE_, \

17 _DEPRECATED_, _DOT_, _EQUALSPACED_, \

18 _immutable_, _invalid_, _module_, _N_A_, \

19 _not_, _SPACE_, _UNDER_, _DNL_ # PYCHOK used!

20# from pygeodesy.named import callname # _MODS, avoid circular

21 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, \

22 _FOR_DOCS, _WARNINGS_X_DEV

23# from pygeodesy.streprs import Fmt # _MODS

24

25 from functools import wraps as _wraps

26

27__all__ = _ALL_LAZY.props

28__version__ = '23.08.23'

29

30_class_ = 'class'

31_dont_use_ = _DEPRECATED_ + ", don't use."

32_function_ = 'function'

33_get_and_set_ = 'get and set'

34_has_been_ = 'has been' # PYCHOK used!

35_method_ = 'method'

36_not_an_inst_ = _not_(_an_, 'instance')

37

38

39 def _allPropertiesOf(Clas_or_inst, *Bases):

40 '''(INTERNAL) Yield all C{R/property/_RO}s at C{Clas_or_inst}

41 as specified in the C{Bases} arguments.

42 '''

43 if _isclass(Clas_or_inst):

44 S = Clas_or_inst, # just this Clas

45 else: # class and super-classes of inst

46 try:

47 S = Clas_or_inst.__class__.__mro__[:-1] # not object

48 except AttributeError:

49 raise

50 S = () # not an inst

51 B = Bases or _PropertyBase

52 for C in S:

53 for n, p in C.__dict__.items():

54 if isinstance(p, B) and p.name == n:

55 yield p

56

57

58 def _allPropertiesOf_n(n, Clas_or_inst, *Bases):

59 '''(INTERNAL) Assert the number of C{R/property/_RO}s at C{Clas_or_inst}.

60 '''

61 t = tuple(p.name for p in _allPropertiesOf(Clas_or_inst, *Bases))

62 if len(t) != n:

63 raise _AssertionError(_COMMASPACE_.join(t), Clas_or_inst,

64 txt=_COMMASPACE_(len(t), _not_(n)))

65 return t

66

67

68 def _hasProperty(inst, name, *Classes): # in .named._NamedBase._update

69 '''(INTERNAL) Check whether C{inst} has a C{P/property/_RO} by this C{name}.

70 '''

71 p = getattr(inst.__class__, name, None) # walks __class__.__mro__

72 return bool(p and isinstance(p, Classes or _PropertyBase)

73 and p.name == name)

74

75

76 def _isclass(obj):

77 '''(INTERNAL) Get and overwrite C{_isclass}.

78 '''

79 f = _MODS.basics.isclass

80 # assert __name__.endswith('.props')

81 _MODS.props._isclass = f

82 return f(obj)

83

84

85 def _update_all(inst, *attrs, **Base):

86 '''(INTERNAL) Zap all I{cached} L{property_RO}s, L{Property}s,

87 L{Property_RO}s and the named C{attrs} of an instance.

88

89 @return: The number of updates (C{int}), if any.

90 '''

91 if _isclass(inst):

92 raise _AssertionError(inst, txt=_not_an_inst_)

93 try:

94 d = inst.__dict__

95 except AttributeError:

96 return 0

97 u = len(d)

98 if u:

99 B = _xkwds_get(Base, Base=_PropertyBase)

100 for p in _allPropertiesOf(inst, B):

101 p._update(inst) # d.pop(p.name, None)

102

103 if attrs:

104 _update_attrs(inst, *attrs) # remove attributes from inst.__dict__

105 u -= len(d)

106 return u # updates

107

108

109# def _update_all_from(inst, other, **Base):

110# '''(INTERNAL) Update all I{cached} L{Property}s and

111# L{Property_RO}s of instance C{inst} from C{other}.

112#

113# @return: The number of updates (C{int}), if any.

114# '''

115# if _isclass(inst):

116# raise _AssertionError(inst, txt=_not_an_inst_)

117# try:

118# d = inst.__dict__

119# f = other.__dict__

120# except AttributeError:

121# return 0

122# u = len(f)

123# if u:

124# u = len(d)

125# B = _xkwds_get(Base, Base=_PropertyBase)

126# for p in _allPropertiesOf(inst, B):

127# p._update_from(inst, other)

128# u -= len(d)

129# return u # number of updates

130

131

132 def _update_attrs(inst, *attrs):

133 '''(INTERNAL) Zap all named C{attrs} of an instance.

134

135 @return: The number of updates (C{int}), if any.

136 '''

137 try:

138 d = inst.__dict__

139 except AttributeError:

140 return 0

141 u = len(d)

142 if u: # zap attrs from inst.__dict__

143 _p = d.pop

144 for a in attrs:

145 _ = _p(a, MISSING)

146# if _ is MISSING and not hasattr(inst, a):

147# n = _MODS.named.classname(inst, prefixed=True)

148# a = _DOT_(n, _SPACE_(a, _invalid_))

149# raise _AssertionError(a, txt=repr(inst))

150# _ = _p(a, None) # redo: hasattr side effect

151 u -= len(d)

152 # assert u >= 0

153 return u # number of named C{attrs} zapped

154

155

156 class _PropertyBase(property):

157 '''(INTERNAL) Base class for C{P/property/_RO}.

158 '''

159 def __init__(self, method, fget, fset, doc=NN):

160

161 if not callable(method):

162 self.getter(method) # PYCHOK no cover

163

164 self.method = method

165 self.name = method.__name__

166 d = doc or method.__doc__

167 if _FOR_DOCS and d:

168 self.__doc__ = d # PYCHOK no cover

169

170 property.__init__(self, fget, fset, self._fdel, d or _N_A_)

171

172 def _fdel(self, inst):

173 '''Zap the I{cached/memoized} C{property} value.

174 '''

175 self._update(inst, None) # PYCHOK no cover

176

177 def _fget(self, inst):

178 '''Get and I{cache/memoize} the C{property} value.

179 '''

180 try: # to get the value cached in instance' __dict__

181 return inst.__dict__[self.name]

182 except KeyError:

183 # cache the value in the instance' __dict__

184 inst.__dict__[self.name] = val = self.method(inst)

185 return val

186

187 def _fset_error(self, inst, val):

188 '''Throws an C{AttributeError}, always.

189 '''

190 n = _MODS.named.classname(inst)

191 n = _DOT_(n, self.name)

192 n = _EQUALSPACED_(n, repr(val))

193 raise self._Error(_immutable_, n, None)

194

195 def _update(self, inst, *unused):

196 '''(INTERNAL) Zap the I{cached/memoized} C{inst.__dict__[name]} item.

197 '''

198 inst.__dict__.pop(self.name, None) # name, NOT _name

199

200 def _update_from(self, inst, other):

201 '''(INTERNAL) Copy a I{cached/memoized} C{inst.__dict__[name]} item

202 from C{other.__dict__[name]} if present, otherwise zap it.

203 '''

204 n = self.name # name, NOT _name

205 v = other.__dict__.get(n, MISSING)

206 if v is MISSING:

207 inst.__dict__.pop(n, None)

208 else:

209 inst.__dict__[n] = v

210

211 def deleter(self, fdel):

212 '''Throws an C{AttributeError}, always.

213 '''

214 raise self._Error(_invalid_, self.deleter, fdel)

215

216 def getter(self, fget):

217 '''Throws an C{AttributeError}, always.

218 '''

219 raise self._Error(_invalid_, self.getter, fget)

220

221 def setter(self, fset):

222 '''Throws an C{AttributeError}, always.

223 '''

224 raise self._Error(_immutable_, self.setter, fset)

225

226 def _Error(self, kind, nameter, farg):

227 '''(INTERNAL) Return an C{AttributeError} instance.

228 '''

229 if farg:

230 n = _DOT_(self.name, nameter.__name__)

231 n = _SPACE_(n, farg.__name__)

232 else:

233 n = nameter

234 e = _SPACE_(kind, _MODS.named.classname(self))

235 return _AttributeError(e, txt=n)

236

237

238 class Property_RO(_PropertyBase):

239 # No __doc__ on purpose

240 def __init__(self, method, doc=NN): # PYCHOK expected

241 '''New I{immutable}, I{caching}, I{memoizing} C{property} I{Factory}

242 to be used as C{decorator}.

243

244 @arg method: The callable being decorated as this C{property}'s C{getter},

245 to be invoked only once.

246 @kwarg doc: Optional property documentation (C{str}).

247

248 @note: Like standard Python C{property} without a C{setter}, but with

249 a more descriptive error message when set.

250

251 @see: Python 3's U{functools.cached_property<https://docs.Python.org/3/

252 library/functools.html#functools.cached_property>} and U{-.cache

253 <https://Docs.Python.org/3/library/functools.html#functools.cache>}

254 to I{cache} or I{memoize} the property value.

255

256 @see: Luciano Ramalho, "Fluent Python", page 636, O'Reilly, Example

257 19-24, 2016 p. 636 or Example 22-28, 2022 p. 869+ and U{class

258 Property<https://docs.Python.org/3/howto/descriptor.html>}.

259 '''

260 _fget = method if _FOR_DOCS else self._fget # XXX force method.__doc__ to epydoc

261 _PropertyBase.__init__(self, method, _fget, self._fset_error)

262

263 def __get__(self, inst, *unused): # PYCHOK 2 vs 3 args

264 if inst is None:

265 return self

266 try: # to get the cached value immediately

267 return inst.__dict__[self.name]

268 except (AttributeError, KeyError):

269 return self._fget(inst)

270

271

272 class Property(Property_RO):

273 # No __doc__ on purpose

274 __init__ = Property_RO.__init__

275 '''New I{mutable}, I{caching}, I{memoizing} C{property} I{Factory}

276 to be used as C{decorator}.

277

278 @see: L{Property_RO} for more details.

279

280 @note: Unless and until the C{setter} is defined, this L{Property} behaves

281 like an I{immutable}, I{caching}, I{memoizing} L{Property_RO}.

282 '''

283

284 def setter(self, method):

285 '''Make this C{Property} I{mutable}.

286

287 @arg method: The callable being decorated as this C{Property}'s C{setter}.

288

289 @note: Setting a new property value always clears the previously I{cached}

290 or I{memoized} value I{after} invoking the B{C{method}}.

291 '''

292 if not callable(method):

293 _PropertyBase.setter(self, method) # PYCHOK no cover

294

295 if _FOR_DOCS: # XXX force method.__doc__ into epydoc

296 _PropertyBase.__init__(self, self.method, self.method, method)

297 else:

298

299 def _fset(inst, val):

300 '''Set and I{cache}, I{memoize} the C{property} value.

301 '''

302 method(inst, val)

303 self._update(inst) # un-cache this item

304

305 # class Property <https://docs.Python.org/3/howto/descriptor.html>

306 _PropertyBase.__init__(self, self.method, self._fget, _fset)

307 return self

308

309

310 class property_RO(_PropertyBase):

311 # No __doc__ on purpose

312 _uname = NN

313

314 def __init__(self, method, doc=NN): # PYCHOK expected

315 '''New I{immutable}, standard C{property} to be used as C{decorator}.

316

317 @arg method: The callable being decorated as C{property}'s C{getter}.

318 @kwarg doc: Optional property documentation (C{str}).

319

320 @note: Like standard Python C{property} without a setter, but with

321 a more descriptive error message when set.

322

323 @see: L{Property_RO}.

324 '''

325 _PropertyBase.__init__(self, method, method, self._fset_error, doc=doc)

326 self._uname = NN(_UNDER_, self.name) # actual attr UNDER<name>

327

328 def _update(self, inst, *Clas): # PYCHOK signature

329 '''(INTERNAL) Zap the I{cached} C{B{inst}.__dict__[_name]} item.

330 '''

331 uname = self._uname

332 if uname in inst.__dict__:

333 if Clas: # overrides inst.__class__

334 d = Clas[0].__dict__.get(uname, MISSING)

335 else:

336 d = getattr(inst.__class__, uname, MISSING)

337# if d is MISSING: # XXX superfluous

338# for c in inst.__class__.__mro__[:-1]:

339# if uname in c.__dict__:

340# d = c.__dict__[uname]

341# break

342 if d is None: # remove inst value

343 inst.__dict__.pop(uname)

344

345

346 class _NamedProperty(property):

347 '''Class C{property} with retrievable name.

348 '''

349 @Property_RO

350 def name(self):

351 '''Get the name of this C{property} (C{str}).

352 '''

353 return self.fget.__name__

354

355

356 def property_doc_(doc):

357 '''Decorator for a standard C{property} with basic documentation.

358

359 @arg doc: The property documentation (C{str}).

360

361 @example:

362

363 >>> @property_doc_("documentation text.")

364 >>> def name(self):

365 >>> ...

366 >>>

367 >>> @name.setter

368 >>> def name(self, value):

369 >>> ...

370 '''

371 # See Luciano Ramalho, "Fluent Python", O'Reilly, Example 7-23,

372 # 2016 p. 212+, 2022 p. 331+, Example 9-22 and <https://

373 # Python-3-Patterns-Idioms-Test.ReadTheDocs.io/en/latest/PythonDecorators.html>

374

375 def _documented_property(method):

376 '''(INTERNAL) Return the documented C{property}.

377 '''

378 t = _get_and_set_ if doc.startswith(_SPACE_) else NN

379 return _NamedProperty(method, None, None, NN('Property to ', t, doc))

380

381 return _documented_property

382

383

384 def _deprecated(call, kind, qual_d):

385 '''(INTERNAL) Decorator for DEPRECATED functions, methods, etc.

386

387 @see: Brett Slatkin, "Effective Python", page 105, 2nd ed,

388 Addison-Wesley, 2019.

389 '''

390 doc = _docof(call)

391

392 @_wraps(call) # PYCHOK self?

393 def _deprecated_call(*args, **kwds):

394 if qual_d: # function

395 q = qual_d

396 elif args: # method

397 q = _qualified(args[0], call.__name__)

398 else: # PYCHOK no cover

399 q = call.__name__

400 _throwarning(kind, q, doc)

401 return call(*args, **kwds)

402

403 return _deprecated_call

404

405

406 def deprecated_class(cls_or_class):

407 '''Use inside __new__ or __init__ of a DEPRECATED class.

408

409 @arg cls_or_class: The class (C{cls} or C{Class}).

410

411 @note: NOT a decorator!

412 '''

413 if _WARNINGS_X_DEV:

414 q = _DOT_(cls_or_class.__module__, cls_or_class.__name__)

415 _throwarning(_class_, q, cls_or_class.__doc__)

416

417

418 def deprecated_function(call):

419 '''Decorator for a DEPRECATED function.

420

421 @arg call: The deprecated function (C{callable}).

422

423 @return: The B{C{call}} DEPRECATED.

424 '''

425 return _deprecated(call, _function_, _DOT_(

426 call.__module__, call.__name__)) if \

427 _WARNINGS_X_DEV else call

428

429

430 def deprecated_method(call):

431 '''Decorator for a DEPRECATED method.

432

433 @arg call: The deprecated method (C{callable}).

434

435 @return: The B{C{call}} DEPRECATED.

436 '''

437 return _deprecated(call, _method_, NN) if _WARNINGS_X_DEV else call

438

439

440 def _deprecated_module(name): # PYCHOK no cover

441 '''(INTERNAL) Callable within a DEPRECATED module.

442 '''

443 if _WARNINGS_X_DEV:

444 _throwarning(_module_, name, _dont_use_)

445

446

447 if _WARNINGS_X_DEV:

448 class deprecated_property(_PropertyBase):

449 '''Decorator for a DEPRECATED C{property} or C{Property}.

450 '''

451 def __init__(self, method):

452 '''Decorator for a DEPRECATED C{property} or C{Property} getter.

453 '''

454 doc = _docof(method)

455

456 def _fget(inst): # PYCHOK no cover

457 '''Get the C{property} or C{Property} value.

458 '''

459 q = _qualified(inst, self.name)

460 _throwarning(property.__name__, q, doc)

461 return self.method(inst) # == method

462

463 _PropertyBase.__init__(self, method, _fget, None, doc=doc)

464

465 def setter(self, method):

466 '''Decorator for a DEPRECATED C{property} or C{Property} setter.

467

468 @arg method: The callable being decorated as this C{Property}'s C{setter}.

469

470 @note: Setting a new property value always clears the previously I{cached}

471 or I{memoized} value I{after} invoking the B{C{method}}.

472 '''

473 if not callable(method):

474 _PropertyBase.setter(self, method) # PYCHOK no cover

475

476 if _FOR_DOCS: # XXX force method.__doc__ into epydoc

477 _PropertyBase.__init__(self, self.method, self.method, method)

478 else:

479

480 def _fset(inst, val):

481 '''Set the C{property} or C{Property} value.

482 '''

483 q = _qualified(inst, self.name)

484 _throwarning(property.__name__, q, _docof(method))

485 method(inst, val)

486 # self._update(inst) # un-cache this item

487

488 # class Property <https://docs.Python.org/3/howto/descriptor.html>

489 _PropertyBase.__init__(self, self.method, self._fget, _fset)

490 return self

491

492 else: # PYCHOK no cover

493 class deprecated_property(property): # PYCHOK expected

494 '''Decorator for a DEPRECATED C{property} or C{Property}.

495 '''

496 pass

497

498 deprecated_Property = deprecated_property

499

500

501 def deprecated_Property_RO(method):

502 '''Decorator for a DEPRECATED L{Property_RO}.

503

504 @arg method: The C{Property_RO.fget} method (C{callable}).

505

506 @return: The B{C{method}} DEPRECATED.

507 '''

508 return _deprecated_RO(method, Property_RO)

509

510

511 def deprecated_property_RO(method):

512 '''Decorator for a DEPRECATED L{property_RO}.

513

514 @arg method: The C{property_RO.fget} method (C{callable}).

515

516 @return: The B{C{method}} DEPRECATED.

517 '''

518 return _deprecated_RO(method, property_RO)

519

520

521 def _deprecated_RO(method, _RO):

522 '''(INTERNAL) Create a DEPRECATED C{property_RO} or C{Property_RO}.

523 '''

524 doc = _docof(method)

525

526 if _WARNINGS_X_DEV:

527

528 class _Deprecated_RO(_PropertyBase):

529 __doc__ = doc

530

531 def __init__(self, method):

532 _PropertyBase.__init__(self, method, self._fget, self._fset_error, doc=doc)

533

534 def _fget(self, inst): # PYCHOK no cover

535 q = _qualified(inst, self.name)

536 _throwarning(_RO.__name__, q, doc)

537 return self.method(inst)

538

539 return _Deprecated_RO(method)

540 else: # PYCHOK no cover

541 return _RO(method, doc=doc)

542

543

544 def _docof(obj):

545 '''(INTERNAL) Get uniform DEPRECATED __doc__ string.

546 '''

547 try:

548 d = obj.__doc__.strip()

549 i = d.find(_DEPRECATED_)

550 except AttributeError:

551 i = -1

552 return _DOT_(_DEPRECATED_, NN) if i < 0 else d[i:]

553

554

555 def _qualified(inst, name):

556 '''(INTERNAL) Fully qualify a name.

557 '''

558 # _DOT_(inst.classname, name), not _DOT_(inst.named4, name)

559 c = inst.__class__

560 q = _DOT_(c.__module__, c.__name__, name)

561 return q

562

563

564 class DeprecationWarnings(object):

565 '''(INTERNAL) Handle C{DeprecationWaring}s.

566 '''

567 _Warnings = 0

568

569 def __call__(self): # for backward compatibility

570 '''Have any C{DeprecationWarning}s been reported or raised?

571

572 @return: The number of C{DeprecationWarning}s (C{int}) so

573 far or C{None} if not enabled.

574

575 @note: To get C{DeprecationWarning}s if any, run C{python}

576 with env var C{PYGEODESY_WARNINGS} set to a non-empty

577 string I{AND} use C{python[3]} command line option

578 C{-X dev}, C{-W always} or C{-W error}, etc.

579 '''

580 return self.Warnings

581

582 def throw(self, kind, name, doc, **stacklevel): # stacklevel=3

583 '''Report or raise a C{DeprecationWarning}.

584 '''

585 line = doc.split(_DNL_, 1)[0].strip()

586 name = _MODS.streprs.Fmt.CURLY(L=name)

587 text = _SPACE_(kind, name, _has_been_, *line.split())

588 kwds = _xkwds(stacklevel, stacklevel=3)

589 # XXX invoke warn or raise DeprecationWarning(text)

590 self._warn(text, category=DeprecationWarning, **kwds)

591 self._Warnings += 1

592

593 @Property_RO

594 def _warn(self):

595 '''Get Python's C{warnings.warn}.

596 '''

597 from warnings import warn

598 return warn

599

600 @property_RO

601 def Warnings(self):

602 '''Get the number of C{DeprecationWarning}s (C{int}) so

603 far or C{None} if not enabled.

604 '''

605 return self._Warnings if _WARNINGS_X_DEV else None

606

607 DeprecationWarnings = DeprecationWarnings() # PYCHOK singleton

608_throwarning = DeprecationWarnings.throw

609

610# **) MIT License

611#

612# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.

613#

614# Permission is hereby granted, free of charge, to any person obtaining a

615# copy of this software and associated documentation files (the "Software"),

616# to deal in the Software without restriction, including without limitation

617# the rights to use, copy, modify, merge, publish, distribute, sublicense,

618# and/or sell copies of the Software, and to permit persons to whom the

619# Software is furnished to do so, subject to the following conditions:

620#

621# The above copyright notice and this permission notice shall be included

622# in all copies or substantial portions of the Software.

623#

624# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

625# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

626# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

627# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

628# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

629# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

630# OTHER DEALINGS IN THE SOFTWARE.