# Coverage for pygeodesy/props.py : 99%

## 152 statements 150 run 2 missing 35 excluded

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 | # -*- coding: utf-8 -*- u'''Im-/mutable, caching or memoizing properties and decorators for C{DeprecationWarning}s. To enable C{DeprecationWarning}s from C{PyGeodesy}, set environment variable C{PYGEODESY_WARNINGS} to a non-empty string and run C{python} with command line option C{-X dev} or one or the C{-W} choices, see function L{DeprecationWarnings} below. @newfield example: Example, Examples ''' from pygeodesy.errors import _AssertionError, _AttributeError, _xkwds from pygeodesy.interns import NN, _DOT_, _EQUALSPACED_, _immutable_, \ _invalid_, MISSING, _N_A_, _SPACE_, _UNDER_ from pygeodesy.lazily import _ALL_LAZY, _env, _FOR_DOCS, \ _PYTHON_X_DEV, _sys from pygeodesy.streprs import Fmt from functools import wraps as _wraps from warnings import warn as _warn __all__ = _ALL_LAZY.props __version__ = '21.02.25' _DEPRECATED_ = 'DEPRECATED' _dont_use_ = _DEPRECATED_ + ", don't use." _Warnings = 0 _W_DEV = (bool(_sys.warnoptions) or _PYTHON_X_DEV) \ and _env.get('PYGEODESY_WARNINGS', NN) def _hasProperty(inst, name, *Classes): '''(INTERNAL) Check whether C{inst} has a C{P/property/_RO} by this C{name}. ''' ps = Classes if Classes else _PropertyBase for c in inst.__class__.__mro__[:-1]: p = c.__dict__.get(name, None) if isinstance(p, ps) and p.name == name: return True return False def _update_all(inst, *attrs): '''(INTERNAL) Zap all I{cached} L{property_RO}s, L{Property_RO}s and the named C{attrs} from an instance' C{__dict__}. @return: The number of updates (C{int}), if any. ''' d = inst.__dict__ u = len(d) for c in inst.__class__.__mro__[:-1]: for n, p in c.__dict__.items(): if isinstance(p, _PropertyBase) and p.name == n: p._update(inst, c) p = d.pop for a in attrs: # PYCHOK no cover if hasattr(inst, a): p(a, None) else: from pygeodesy.named import classname n = classname(inst, prefixed=True) a = _DOT_(n, _SPACE_(a, _invalid_)) raise _AssertionError(a, txt=repr(inst)) return u - len(d) # of updates class _PropertyBase(property): '''(INTERNAL) Base class for C{P/property/_RO}. ''' def __init__(self, method, fget, fset, doc=NN): if not callable(method): self.getter(method) # PYCHOK no cover self.method = method self.name = method.__name__ d = doc or method.__doc__ if _FOR_DOCS and d: self.__doc__ = d # PYCHOK no cover property.__init__(self, fget, fset, self._fdel, d or _N_A_) def _fdel(self, inst): # deleter self._update(inst, None) # PYCHOK no cover def _fget(self, inst): try: # to get the value cached in instance' __dict__ return inst.__dict__[self.name] except KeyError: # cache the value in the instance' __dict__ inst.__dict__[self.name] = val = self.method(inst) return val def _fset_error(self, inst, val): '''Throws an C{AttributeError}, always. ''' from pygeodesy.named import classname n = _DOT_(classname(inst), self.name) self._immutable_error(_EQUALSPACED_(n, repr(val))) def _immutable_error(self, name): from pygeodesy.named import classname e = _SPACE_(_immutable_, classname(self)) raise _AttributeError(e, txt=name) def _invalid_error(self, name): from pygeodesy.named import classname e = _SPACE_(_invalid_, classname(self)) raise _AttributeError(e, txt=name) def _update(self, inst, *unused): '''(INTERNAL) Zap the I{cached} C{inst.__dict__[name]} item. ''' inst.__dict__.pop(self.name, None) def deleter(self, fdel): '''Throws an C{AttributeError}, always. ''' n = _DOT_(self.name, self.deleter.__name__) self._invalid_error(_SPACE_(n, fdel.__name__)) def getter(self, fget): '''Throws an C{AttributeError}, always. ''' n = _DOT_(self.name, self.getter.__name__) self._invalid_error(_SPACE_(n, fget.__name__)) def setter(self, fset): '''Throws an C{AttributeError}, always. ''' n = _DOT_(self.name, self.setter.__name__) self._immutable_error(_SPACE_(n, fset.__name__)) class Property_RO(_PropertyBase): # No __doc__ on purpose def __init__(self, method, doc=NN): # PYCHOK expected '''New I{immutable}, I{caching}, I{memoizing} C{property} I{Factory} to be used as C{decorator}. @arg method: The callable being decorated as this C{property}'s C{getter}, to be invoked only once. @kwarg doc: Optional property documentation (C{str}). @note: Like standard Python C{property} without a C{setter}, but with a more descriptive error message when set. @see: Python 3's U{functools.cached_property<https://docs.Python.org/3/ library/functools.html#functools.cached_property>} and U{-.cache <https://Docs.Python.org/3/library/functools.html#functools.cache>} to I{cache} or I{memoize} the property value. @see: Luciano Ramalho, "Fluent Python", page 636, O'Reilly, 2016, "Coding a Property Factory", especially Example 19-24 and U{class Property<https://docs.Python.org/3/howto/descriptor.html>}. ''' _PropertyBase.__init__(self, method, self._fget, self._fset_error) def __get__(self, inst, *unused): # PYCHOK 2 vs 3 args if inst is None: return self try: # to get the cached value immediately return inst.__dict__[self.name] except (AttributeError, KeyError): return self._fget(inst) class Property(Property_RO): # No __doc__ on purpose __init__ = Property_RO.__init__ '''New I{mutable}, I{caching}, I{memoizing} C{property} I{Factory} to be used as C{decorator}. @see: L{Property_RO} for more details. @note: Unless and until the C{setter} is defined, this L{Property} behaves like an I{immutable}, I{caching}, I{memoizing} L{Property_RO}. ''' def setter(self, method): '''Make this C{Property} I{mutable}. @arg method: The callable being decorated as this C{Property}'s C{setter}. @note: Setting a new property value always clears the previously I{cached} or I{memoized} value I{after} invoking the B{C{method}}. ''' if not callable(method): _PropertyBase.setter(self, method) # PYCHOK no cover def _fset(inst, val): method(inst, val) self._update(inst) # un-cache this item # class Property <https://docs.Python.org/3/howto/descriptor.html> _PropertyBase.__init__(self, self.method, self._fget, _fset) return self class property_RO(_PropertyBase): # No __doc__ on purpose _n = NN def __init__(self, method, doc=NN): # PYCHOK expected '''New I{immutable}, standard C{property} to be used as C{decorator}. @arg method: The callable being decorated as C{property}'s C{getter}. @kwarg doc: Optional property documentation (C{str}). @note: Like standard Python C{property} without a setter, but with a more descriptive error message when set. @see: L{Property_RO}. ''' _PropertyBase.__init__(self, method, method, self._fset_error, doc=doc) self._n = NN(_UNDER_, self.name) # actual attr name def _update(self, inst, *Clas): # PYCHOK signature '''(INTERNAL) Zap the I{cached} C{inst.__dict__[_name]} item. ''' _n = self._n if _n in inst.__dict__: if Clas: d = Clas[0].__dict__.get(_n, MISSING) else: d = getattr(inst.__class__, _n, MISSING) # if d is MISSING: # XXX superfluous # for c in inst.__class__.__mro__[:-1]: # if _n in c.__dict__: # d = c.__dict__[_n] # break if d is None: # reset inst value to unavailable inst.__dict__.pop(_n) def property_doc_(doc): '''Decorator for a standard C{property} with basic documentation. @arg doc: The property documentation (C{str}). @example: >>> @property_doc_("documentation text.") >>> def name(self): >>> ... >>> >>> @name.setter >>> def name(self, value): >>> ... ''' # See Luciano Ramalho, "Fluent Python", page 212ff, O'Reilly, 2016, # "Parameterized Decorators", especially Example 7-23. Also, see # <https://Python-3-Patterns-Idioms-Test.ReadTheDocs.io/en/latest/PythonDecorators.html> def _documented_property(method): '''(INTERNAL) Return the documented C{property}. ''' t = 'get and set' if doc.startswith(_SPACE_) else NN return property(method, None, None, NN('Property to ', t, doc)) return _documented_property def _deprecated(call, kind, qual_d): '''(INTERNAL) Decorator for DEPRECATED functions, methods, etc. @see: Brett Slatkin, "Effective Python", page 105, 2nd ed, Addison-Wesley, 2019. ''' doc = _docof(call) @_wraps(call) # PYCHOK self? def _deprecated_call(*args, **kwds): if qual_d: # function q = qual_d elif args: # method q = _qualified(args[0], call.__name__) else: # PYCHOK no cover q = call.__name__ _throwarning(kind, q, doc) return call(*args, **kwds) return _deprecated_call def deprecated_class(Clas): '''Decorator for a DEPRECATED class. @arg Clas: The class (C{class}). @return: The B{C{Clas}} DEPRECATED. ''' if _W_DEV: doc = _docof(Clas) q_d = _DOT_(Clas.__module__, Clas.__name__) # @_wraps(Clas) # XXX? class _Deprecated_Clas(Clas): __doc__ = doc def __init__(self, *args, **kwds): # PYCHOK no cover _throwarning('class', q_d, doc) Clas.__init__(self, *args, **kwds) return _Deprecated_Clas else: # PYCHOK no cover return Clas def deprecated_function(call): '''Decorator for a DEPRECATED function. @arg call: The deprecated function (C{callable}). @return: The B{C{call}} DEPRECATED. ''' return _deprecated(call, 'function', _DOT_( call.__module__, call.__name__)) if \ _W_DEV else call def deprecated_method(call): '''Decorator for a DEPRECATED method. @arg call: The deprecated method (C{callable}). @return: The B{C{call}} DEPRECATED. ''' return _deprecated(call, 'method', NN) if _W_DEV else call def _deprecated_module(name): # PYCHOK no cover '''(INTERNAL) Callable within a DEPRECATED module. ''' if _W_DEV: _throwarning('module', name, _dont_use_) def deprecated_Property_RO(method): '''Decorator for a DEPRECATED L{Property_RO}. @arg method: The C{Property_RO.fget} method (C{callable}). @return: The B{C{method}} DEPRECATED. ''' return _deprecated_RO(method, Property_RO) def deprecated_property_RO(method): '''Decorator for a DEPRECATED L{property_RO}. @arg method: The C{property_RO.fget} method (C{callable}). @return: The B{C{method}} DEPRECATED. ''' return _deprecated_RO(method, property_RO) def _deprecated_RO(method, _RO): '''(INTERNAL) Create a DEPRECATED C{property_RO} or C{Property_RO}. ''' doc = _docof(method) if _W_DEV: class _Deprecated_RO(_PropertyBase): __doc__ = doc def __init__(self, method): _PropertyBase.__init__(self, method, self._fget, self._fset_error, doc=doc) def _fget(self, inst): # PYCHOK no cover q = _qualified(inst, self.name) _throwarning(_RO.__name__, q, doc) return self.method(inst) return _Deprecated_RO(method) else: # PYCHOK no cover return _RO(method, doc=doc) def DeprecationWarnings(): '''Get the C{DeprecationWarning}s reported or raised. @return: The number of C{DeprecationWarning}s (C{int}) or C{None} if not enabled. @note: To get C{DeprecationWarning}s if any, run C{python} with environment variable C{PYGEODESY_WARNINGS} set to a non-empty string AND use C{python} command line option C{-X dev}, C{-W always}, or C{-W error}, etc. ''' return _Warnings if _W_DEV else None def _docof(obj): '''(INTERNAL) Get uniform DEPRECATED __doc__ string. ''' try: d = obj.__doc__.strip() i = d.find(_DEPRECATED_) except AttributeError: # PYCHOK no cover i = -1 return _DOT_(_DEPRECATED_, NN) if i < 0 else d[i:] def _qualified(inst, name): '''(INTERNAL) Fully qualify a name. ''' # _DOT_(inst.classname, name), not _DOT_(inst.named4, name) c = inst.__class__ q = _DOT_(c.__module__, c.__name__, name) return q def _throwarning(kind, name, doc, **stacklevel): # stacklevel=3 '''(INTERNAL) Report or raise a C{DeprecationWarning}. ''' text = _SPACE_(kind, Fmt.CURLY(L=name), 'has been', doc) kwds = _xkwds(stacklevel, stacklevel=3) global _Warnings _Warnings += 1 # XXX _warn or raise DeprecationWarning(text) _warn(text, category=DeprecationWarning, **kwds) # **) MIT License # # Copyright (C) 2016-2021 -- mrJean1 at Gmail -- All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE.