Coverage for pygeodesy/props.py: 98%
205 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-05-06 16:50 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-05-06 16:50 -0400
2# -*- coding: utf-8 -*-
4u'''Mutable, immutable and caching/memoizing properties and
5deprecation decorators.
7To enable C{DeprecationWarning}s from C{PyGeodesy}, set env var
8C{PYGEODESY_WARNINGS} to a non-empty string I{AND} run C{python}
9with command line option C{-X dev} or with one of the C{-W}
10choices, see callable L{DeprecationWarnings} below.
11'''
13from pygeodesy.basics import isclass as _isclass # _MODS
14from pygeodesy.errors import _AssertionError, _AttributeError, \
15 _xkwds, _xkwds_get
16from 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
21from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, \
22 _FOR_DOCS, _WARNINGS_X_DEV
23# from pygeodesy.streprs import Fmt # _MODS
25from functools import wraps as _wraps
27__all__ = _ALL_LAZY.props
28__version__ = '24.05.03'
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')
39def _allPropertiesOf(Clas_or_inst, *Bases, **excls):
40 '''(INTERNAL) Yield all C{R/property/_RO}s at C{Clas_or_inst}
41 as specified in the C{Bases} arguments, except C{excls}.
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 _is = isinstance
53 for C in S:
54 for n, p in C.__dict__.items():
55 if _is(p, B) and p.name == n and n not in excls:
56 yield p
59def _allPropertiesOf_n(n, Clas_or_inst, *Bases, **excls):
60 '''(INTERNAL) Assert the number of C{R/property/_RO}s at C{Clas_or_inst}.
61 '''
62 t = tuple(p.name for p in _allPropertiesOf(Clas_or_inst, *Bases, **excls))
63 if len(t) != n:
64 raise _AssertionError(_COMMASPACE_.join(t), Clas_or_inst,
65 txt=_COMMASPACE_(len(t), _not_(n)))
66 return t
69def _hasProperty(inst, name, *Classes): # in .named._NamedBase._update
70 '''(INTERNAL) Check whether C{inst} has a C{P/property/_RO} by this C{name}.
71 '''
72 p = getattr(inst.__class__, name, None) # walks __class__.__mro__
73 return bool(p and isinstance(p, Classes or _PropertyBase)
74 and p.name == name)
77# def _isclass(obj):
78# '''(INTERNAL) Get and overwrite C{_isclass}.
79# '''
80# _MODS.getmodule(__name__)._isclass = f = _MODS.basics.isclass
81# return f(obj)
84def _update_all(inst, *attrs, **Base_needed):
85 '''(INTERNAL) Zap all I{cached} L{property_RO}s, L{Property}s,
86 L{Property_RO}s and the named C{attrs} of an instance.
88 @return: The number of updates (C{int}), if any.
89 '''
90 if _isclass(inst):
91 raise _AssertionError(inst, txt=_not_an_inst_)
92 try:
93 d = inst.__dict__
94 except AttributeError:
95 return 0
96 u = len(d)
97 if u > _xkwds_get(Base_needed, needed=0):
98 B = _xkwds_get(Base_needed, Base=_PropertyBase)
99 for p in _allPropertiesOf(inst, B):
100 p._update(inst) # d.pop(p.name, None)
102 if attrs:
103 _update_attrs(inst, *attrs) # remove attributes from inst.__dict__
104 u -= len(d)
105 return u # updates
108# def _update_all_from(inst, other, **Base):
109# '''(INTERNAL) Update all I{cached} L{Property}s and
110# L{Property_RO}s of instance C{inst} from C{other}.
111#
112# @return: The number of updates (C{int}), if any.
113# '''
114# if _isclass(inst):
115# raise _AssertionError(inst, txt=_not_an_inst_)
116# try:
117# d = inst.__dict__
118# f = other.__dict__
119# except AttributeError:
120# return 0
121# u = len(f)
122# if u:
123# u = len(d)
124# B = _xkwds_get(Base, Base=_PropertyBase)
125# for p in _allPropertiesOf(inst, B):
126# p._update_from(inst, other)
127# u -= len(d)
128# return u # number of updates
131def _update_attrs(inst, *attrs):
132 '''(INTERNAL) Zap all named C{attrs} of an instance.
134 @return: The number of updates (C{int}), if any.
135 '''
136 try:
137 d = inst.__dict__
138 except AttributeError:
139 return 0
140 u = len(d)
141 if u: # zap attrs from inst.__dict__
142 _p = d.pop
143 for a in attrs:
144 _ = _p(a, MISSING)
145# if _ is MISSING and not hasattr(inst, a):
146# n = _MODS.named.classname(inst, prefixed=True)
147# a = _DOT_(n, _SPACE_(a, _invalid_))
148# raise _AssertionError(a, txt=repr(inst))
149# _ = _p(a, None) # redo: hasattr side effect
150 u -= len(d)
151 # assert u >= 0
152 return u # number of named C{attrs} zapped
155class _PropertyBase(property):
156 '''(INTERNAL) Base class for C{P/property/_RO}.
157 '''
158 def __init__(self, method, fget, fset, doc=NN):
160 if not callable(method):
161 self.getter(method) # PYCHOK no cover
163 self.method = method
164 self.name = method.__name__
165 d = doc or method.__doc__
166 if _FOR_DOCS and d:
167 self.__doc__ = d # PYCHOK no cover
169 property.__init__(self, fget, fset, self._fdel, d or _N_A_)
171 def _Error(self, kind, nameter, farg):
172 '''(INTERNAL) Return an C{AttributeError} instance.
173 '''
174 if farg:
175 n = _DOT_(self.name, nameter.__name__)
176 n = _SPACE_(n, farg.__name__)
177 else:
178 n = nameter
179 e = _SPACE_(kind, _MODS.named.classname(self))
180 return _AttributeError(e, txt=n)
182 def _fdel(self, inst):
183 '''Zap the I{cached/memoized} C{property} value.
184 '''
185 self._update(inst, None) # PYCHOK no cover
187 def _fget(self, inst):
188 '''Get and I{cache/memoize} the C{property} value.
189 '''
190 try: # to get the value cached in instance' __dict__
191 return inst.__dict__[self.name]
192 except KeyError:
193 # cache the value in the instance' __dict__
194 inst.__dict__[self.name] = val = self.method(inst)
195 return val
197 def _fset_error(self, inst, val):
198 '''Throws an C{AttributeError}, always.
199 '''
200 n = _MODS.named.classname(inst)
201 n = _DOT_(n, self.name)
202 n = _EQUALSPACED_(n, repr(val))
203 raise self._Error(_immutable_, n, None)
205 def _update(self, inst, *unused):
206 '''(INTERNAL) Zap the I{cached/memoized} C{inst.__dict__[name]} item.
207 '''
208 inst.__dict__.pop(self.name, None) # name, NOT _name
210 def _update_from(self, inst, other):
211 '''(INTERNAL) Copy a I{cached/memoized} C{inst.__dict__[name]} item
212 from C{other.__dict__[name]} if present, otherwise zap it.
213 '''
214 n = self.name # name, NOT _name
215 v = other.__dict__.get(n, MISSING)
216 if v is MISSING:
217 inst.__dict__.pop(n, None)
218 else:
219 inst.__dict__[n] = v
221 def deleter(self, fdel):
222 '''Throws an C{AttributeError}, always.
223 '''
224 raise self._Error(_invalid_, self.deleter, fdel)
226 def getter(self, fget):
227 '''Throws an C{AttributeError}, always.
228 '''
229 raise self._Error(_invalid_, self.getter, fget)
231 def setter(self, fset):
232 '''Throws an C{AttributeError}, always.
233 '''
234 raise self._Error(_immutable_, self.setter, fset)
237class Property_RO(_PropertyBase):
238 # No __doc__ on purpose
239 def __init__(self, method, doc=NN): # PYCHOK expected
240 '''New I{immutable}, I{caching}, I{memoizing} C{property} I{Factory}
241 to be used as C{decorator}.
243 @arg method: The callable being decorated as this C{property}'s C{getter},
244 to be invoked only once.
245 @kwarg doc: Optional property documentation (C{str}).
247 @note: Like standard Python C{property} without a C{setter}, but with
248 a more descriptive error message when set.
250 @see: Python 3's U{functools.cached_property<https://docs.Python.org/3/
251 library/functools.html#functools.cached_property>} and U{-.cache
252 <https://Docs.Python.org/3/library/functools.html#functools.cache>}
253 to I{cache} or I{memoize} the property value.
255 @see: Luciano Ramalho, "Fluent Python", page 636, O'Reilly, Example
256 19-24, 2016 p. 636 or Example 22-28, 2022 p. 869+ and U{class
257 Property<https://docs.Python.org/3/howto/descriptor.html>}.
258 '''
259 _fget = method if _FOR_DOCS else self._fget # XXX force method.__doc__ to epydoc
260 _PropertyBase.__init__(self, method, _fget, self._fset_error)
262 def __get__(self, inst, *unused): # PYCHOK 2 vs 3 args
263 if inst is None:
264 return self
265 try: # to get the cached value immediately
266 return inst.__dict__[self.name]
267 except (AttributeError, KeyError):
268 return self._fget(inst)
271class Property(Property_RO):
272 # No __doc__ on purpose
273 __init__ = Property_RO.__init__
274 '''New I{mutable}, I{caching}, I{memoizing} C{property} I{Factory}
275 to be used as C{decorator}.
277 @see: L{Property_RO} for more details.
279 @note: Unless and until the C{setter} is defined, this L{Property} behaves
280 like an I{immutable}, I{caching}, I{memoizing} L{Property_RO}.
281 '''
283 def setter(self, method):
284 '''Make this C{Property} I{mutable}.
286 @arg method: The callable being decorated as this C{Property}'s C{setter}.
288 @note: Setting a new property value always clears the previously I{cached}
289 or I{memoized} value I{after} invoking the B{C{method}}.
290 '''
291 if not callable(method):
292 _PropertyBase.setter(self, method) # PYCHOK no cover
294 if _FOR_DOCS: # XXX force method.__doc__ into epydoc
295 _PropertyBase.__init__(self, self.method, self.method, method)
296 else:
298 def _fset(inst, val):
299 '''Set and I{cache}, I{memoize} the C{property} value.
300 '''
301 method(inst, val)
302 self._update(inst) # un-cache this item
304 # class Property <https://docs.Python.org/3/howto/descriptor.html>
305 _PropertyBase.__init__(self, self.method, self._fget, _fset)
306 return self
309class property_RO(_PropertyBase):
310 # No __doc__ on purpose
311 _uname = NN
313 def __init__(self, method, doc=NN): # PYCHOK expected
314 '''New I{immutable}, standard C{property} to be used as C{decorator}.
316 @arg method: The callable being decorated as C{property}'s C{getter}.
317 @kwarg doc: Optional property documentation (C{str}).
319 @note: Like standard Python C{property} without a setter, but with
320 a more descriptive error message when set.
322 @see: L{Property_RO}.
323 '''
324 _PropertyBase.__init__(self, method, method, self._fset_error, doc=doc)
325 self._uname = NN(_UNDER_, self.name) # actual attr UNDER<name>
327 def _update(self, inst, *Clas): # PYCHOK signature
328 '''(INTERNAL) Zap the I{cached} C{B{inst}.__dict__[_name]} item.
329 '''
330 uname = self._uname
331 if uname in inst.__dict__:
332 if Clas: # overrides inst.__class__
333 d = Clas[0].__dict__.get(uname, MISSING)
334 else:
335 d = getattr(inst.__class__, uname, MISSING)
336# if d is MISSING: # XXX superfluous
337# for c in inst.__class__.__mro__[:-1]:
338# if uname in c.__dict__:
339# d = c.__dict__[uname]
340# break
341 if d is None: # remove inst value
342 inst.__dict__.pop(uname)
345class _NamedProperty(property):
346 '''Class C{property} with retrievable name.
347 '''
348 @Property_RO
349 def name(self):
350 '''Get the name of this C{property} (C{str}).
351 '''
352 return self.fget.__name__
355def property_doc_(doc):
356 '''Decorator for a standard C{property} with basic documentation.
358 @arg doc: The property documentation (C{str}).
360 @example:
362 >>> @property_doc_("documentation text.")
363 >>> def name(self):
364 >>> ...
365 >>>
366 >>> @name.setter
367 >>> def name(self, value):
368 >>> ...
369 '''
370 # See Luciano Ramalho, "Fluent Python", O'Reilly, Example 7-23,
371 # 2016 p. 212+, 2022 p. 331+, Example 9-22 and <https://
372 # Python-3-Patterns-Idioms-Test.ReadTheDocs.io/en/latest/PythonDecorators.html>
374 def _documented_property(method):
375 '''(INTERNAL) Return the documented C{property}.
376 '''
377 t = _get_and_set_ if doc.startswith(_SPACE_) else NN
378 return _NamedProperty(method, None, None, NN('Property to ', t, doc))
380 return _documented_property
383def _deprecated(call, kind, qual_d):
384 '''(INTERNAL) Decorator for DEPRECATED functions, methods, etc.
386 @see: Brett Slatkin, "Effective Python", page 105, 2nd ed,
387 Addison-Wesley, 2019.
388 '''
389 doc = _docof(call)
391 @_wraps(call) # PYCHOK self?
392 def _deprecated_call(*args, **kwds):
393 if qual_d: # function
394 q = qual_d
395 elif args: # method
396 q = _qualified(args[0], call.__name__)
397 else: # PYCHOK no cover
398 q = call.__name__
399 _throwarning(kind, q, doc)
400 return call(*args, **kwds)
402 return _deprecated_call
405def deprecated_class(cls_or_class):
406 '''Use inside __new__ or __init__ of a DEPRECATED class.
408 @arg cls_or_class: The class (C{cls} or C{Class}).
410 @note: NOT a decorator!
411 '''
412 if _WARNINGS_X_DEV:
413 q = _DOT_(cls_or_class.__module__, cls_or_class.__name__)
414 _throwarning(_class_, q, cls_or_class.__doc__)
417def deprecated_function(call):
418 '''Decorator for a DEPRECATED function.
420 @arg call: The deprecated function (C{callable}).
422 @return: The B{C{call}} DEPRECATED.
423 '''
424 return _deprecated(call, _function_, _DOT_(
425 call.__module__, call.__name__)) if \
426 _WARNINGS_X_DEV else call
429def deprecated_method(call):
430 '''Decorator for a DEPRECATED method.
432 @arg call: The deprecated method (C{callable}).
434 @return: The B{C{call}} DEPRECATED.
435 '''
436 return _deprecated(call, _method_, NN) if _WARNINGS_X_DEV else call
439def _deprecated_module(name): # PYCHOK no cover
440 '''(INTERNAL) Callable within a DEPRECATED module.
441 '''
442 if _WARNINGS_X_DEV:
443 _throwarning(_module_, name, _dont_use_)
446if _WARNINGS_X_DEV:
447 class deprecated_property(_PropertyBase):
448 '''Decorator for a DEPRECATED C{property} or C{Property}.
449 '''
450 def __init__(self, method):
451 '''Decorator for a DEPRECATED C{property} or C{Property} getter.
452 '''
453 doc = _docof(method)
455 def _fget(inst): # PYCHOK no cover
456 '''Get the C{property} or C{Property} value.
457 '''
458 q = _qualified(inst, self.name)
459 _throwarning(property.__name__, q, doc)
460 return self.method(inst) # == method
462 _PropertyBase.__init__(self, method, _fget, None, doc=doc)
464 def setter(self, method):
465 '''Decorator for a DEPRECATED C{property} or C{Property} setter.
467 @arg method: The callable being decorated as this C{Property}'s C{setter}.
469 @note: Setting a new property value always clears the previously I{cached}
470 or I{memoized} value I{after} invoking the B{C{method}}.
471 '''
472 if not callable(method):
473 _PropertyBase.setter(self, method) # PYCHOK no cover
475 if _FOR_DOCS: # XXX force method.__doc__ into epydoc
476 _PropertyBase.__init__(self, self.method, self.method, method)
477 else:
479 def _fset(inst, val):
480 '''Set the C{property} or C{Property} value.
481 '''
482 q = _qualified(inst, self.name)
483 _throwarning(property.__name__, q, _docof(method))
484 method(inst, val)
485 # self._update(inst) # un-cache this item
487 # class Property <https://docs.Python.org/3/howto/descriptor.html>
488 _PropertyBase.__init__(self, self.method, self._fget, _fset)
489 return self
491else: # PYCHOK no cover
492 class deprecated_property(property): # PYCHOK expected
493 '''Decorator for a DEPRECATED C{property} or C{Property}.
494 '''
495 pass
497deprecated_Property = deprecated_property
500def deprecated_Property_RO(method):
501 '''Decorator for a DEPRECATED L{Property_RO}.
503 @arg method: The C{Property_RO.fget} method (C{callable}).
505 @return: The B{C{method}} DEPRECATED.
506 '''
507 return _deprecated_RO(method, Property_RO)
510def deprecated_property_RO(method):
511 '''Decorator for a DEPRECATED L{property_RO}.
513 @arg method: The C{property_RO.fget} method (C{callable}).
515 @return: The B{C{method}} DEPRECATED.
516 '''
517 return _deprecated_RO(method, property_RO)
520def _deprecated_RO(method, _RO):
521 '''(INTERNAL) Create a DEPRECATED C{property_RO} or C{Property_RO}.
522 '''
523 doc = _docof(method)
525 if _WARNINGS_X_DEV:
527 class _Deprecated_RO(_PropertyBase):
528 __doc__ = doc
530 def __init__(self, method):
531 _PropertyBase.__init__(self, method, self._fget, self._fset_error, doc=doc)
533 def _fget(self, inst): # PYCHOK no cover
534 q = _qualified(inst, self.name)
535 _throwarning(_RO.__name__, q, doc)
536 return self.method(inst)
538 return _Deprecated_RO(method)
539 else: # PYCHOK no cover
540 return _RO(method, doc=doc)
543def _docof(obj):
544 '''(INTERNAL) Get uniform DEPRECATED __doc__ string.
545 '''
546 try:
547 d = obj.__doc__.strip()
548 i = d.find(_DEPRECATED_)
549 except AttributeError:
550 i = -1
551 return _DOT_(_DEPRECATED_, NN) if i < 0 else d[i:]
554def _qualified(inst, name):
555 '''(INTERNAL) Fully qualify a name.
556 '''
557 # _DOT_(inst.classname, name), not _DOT_(inst.named4, name)
558 c = inst.__class__
559 q = _DOT_(c.__module__, c.__name__, name)
560 return q
563class DeprecationWarnings(object):
564 '''(INTERNAL) Handle C{DeprecationWaring}s.
565 '''
566 _Warnings = 0
568 def __call__(self): # for backward compatibility
569 '''Have any C{DeprecationWarning}s been reported or raised?
571 @return: The number of C{DeprecationWarning}s (C{int}) so
572 far or C{None} if not enabled.
574 @note: To get C{DeprecationWarning}s if any, run C{python}
575 with env var C{PYGEODESY_WARNINGS} set to a non-empty
576 string I{AND} use C{python[3]} command line option
577 C{-X dev}, C{-W always} or C{-W error}, etc.
578 '''
579 return self.Warnings
581 def throw(self, kind, name, doc, **stacklevel): # stacklevel=3
582 '''Report or raise a C{DeprecationWarning}.
583 '''
584 line = doc.split(_DNL_, 1)[0].strip()
585 name = _MODS.streprs.Fmt.CURLY(L=name)
586 text = _SPACE_(kind, name, _has_been_, *line.split())
587 kwds = _xkwds(stacklevel, stacklevel=3)
588 # XXX invoke warn or raise DeprecationWarning(text)
589 self._warn(text, category=DeprecationWarning, **kwds)
590 self._Warnings += 1
592 @Property_RO
593 def _warn(self):
594 '''Get Python's C{warnings.warn}.
595 '''
596 from warnings import warn
597 return warn
599 @property_RO
600 def Warnings(self):
601 '''Get the number of C{DeprecationWarning}s (C{int}) so
602 far or C{None} if not enabled.
603 '''
604 return self._Warnings if _WARNINGS_X_DEV else None
606DeprecationWarnings = DeprecationWarnings() # PYCHOK singleton
607_throwarning = DeprecationWarnings.throw
609# **) MIT License
610#
611# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
612#
613# Permission is hereby granted, free of charge, to any person obtaining a
614# copy of this software and associated documentation files (the "Software"),
615# to deal in the Software without restriction, including without limitation
616# the rights to use, copy, modify, merge, publish, distribute, sublicense,
617# and/or sell copies of the Software, and to permit persons to whom the
618# Software is furnished to do so, subject to the following conditions:
619#
620# The above copyright notice and this permission notice shall be included
621# in all copies or substantial portions of the Software.
622#
623# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
624# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
625# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
626# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
627# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
628# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
629# OTHER DEALINGS IN THE SOFTWARE.