Coverage for pygeodesy/named.py: 96%
451 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-12-29 12:35 -0500
« prev ^ index » next coverage.py v7.2.2, created at 2023-12-29 12:35 -0500
2# -*- coding: utf-8 -*-
4u'''(INTERNAL) Nameable class instances.
6Classes C{_Named}, C{_NamedDict}, C{_NamedEnum}, C{_NamedEnumItem} and
7C{_NamedTuple} and several subclasses thereof, all with nameable instances.
9The items in a C{_NamedDict} are accessable as attributes and the items
10in a C{_NamedTuple} are named to be accessable as attributes, similar to
11standard Python C{namedtuple}s.
13@see: Module L{pygeodesy.namedTuples} for (most of) the C{Named-Tuples}.
14'''
16from pygeodesy.basics import isclass, isidentifier, iskeyword, isstr, issubclassof, \
17 len2, _sizeof, _xcopy, _xdup, _zip
18from pygeodesy.errors import _AssertionError, _AttributeError, _incompatible, \
19 _IndexError, _IsnotError, itemsorted, LenError, \
20 _NameError, _NotImplementedError, _TypeError, \
21 _TypesError, _ValueError, UnitError, _xattr, _xkwds, \
22 _xkwds_get, _xkwds_pop, _xkwds_popitem
23from pygeodesy.interns import NN, _at_, _AT_, _COLON_, _COLONSPACE_, _COMMA_, \
24 _COMMASPACE_, _doesn_t_exist_, _DOT_, _DUNDER_, \
25 _EQUAL_, _EQUALSPACED_, _exists_, _immutable_, _name_, \
26 _NL_, _NN_, _not_, _other_, _s_, _SPACE_, _std_, \
27 _UNDER_, _valid_, _vs_, _dunder_nameof, _isPyPy, _under
28from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS, _caller3, _getenv
29from pygeodesy.props import _allPropertiesOf_n, deprecated_method, _hasProperty, \
30 _update_all, property_doc_, Property_RO, property_RO, \
31 _update_attrs
32from pygeodesy.streprs import attrs, Fmt, lrstrip, pairs, reprs, unstr
34__all__ = _ALL_LAZY.named
35__version__ = '23.12.03'
37_COMMANL_ = _COMMA_ + _NL_
38_COMMASPACEDOT_ = _COMMASPACE_ + _DOT_
39_del_ = 'del'
40_item_ = 'item'
41_MRO_ = 'MRO'
42# __DUNDER gets mangled in class
43_name = _under(_name_)
44_Names_ = '_Names_'
45_registered_ = 'registered' # PYCHOK used!
46_std_NotImplemented = _getenv('PYGEODESY_NOTIMPLEMENTED', NN).lower() == _std_
47_Units_ = '_Units_'
50def _xjoined_(prefix, name):
51 '''(INTERNAL) Join C{pref} and non-empty C{name}.
52 '''
53 return _SPACE_(prefix, repr(name)) if name and prefix else (prefix or name)
56def _xnamed(inst, name, force=False):
57 '''(INTERNAL) Set the instance' C{.name = B{name}}.
59 @arg inst: The instance (C{_Named}).
60 @arg name: The name (C{str}).
61 @kwarg force: Force name change (C{bool}).
63 @return: The B{C{inst}}, named if B{C{force}}d or
64 not named before.
65 '''
66 if name and isinstance(inst, _Named):
67 if not inst.name:
68 inst.name = name
69 elif force:
70 inst.rename(name)
71 return inst
74def _xother3(inst, other, name=_other_, up=1, **name_other):
75 '''(INTERNAL) Get C{name} and C{up} for a named C{other}.
76 '''
77 if name_other: # and not other and len(name_other) == 1
78 name, other = _xkwds_popitem(name_other)
79 elif other and len(other) == 1:
80 other = other[0]
81 else:
82 raise _AssertionError(name, other, txt=classname(inst, prefixed=True))
83 return other, name, up
86def _xotherError(inst, other, name=_other_, up=1):
87 '''(INTERNAL) Return a C{_TypeError} for an incompatible, named C{other}.
88 '''
89 n = _callname(name, classname(inst, prefixed=True), inst.name, up=up + 1)
90 return _TypeError(name, other, txt=_incompatible(n))
93def _xvalid(name, _OK=False):
94 '''(INTERNAL) Check valid attribute name C{name}.
95 '''
96 return True if (name and isstr(name)
97 and name != _name_
98 and (_OK or not name.startswith(_UNDER_))
99 and (not iskeyword(name))
100 and isidentifier(name)) else False
103class _Dict(dict):
104 '''(INTERNAL) An C{dict} with both key I{and}
105 attribute access to the C{dict} items.
106 '''
107 _iteration = None # Iteration number (C{int}) or C{None}
109 def __getattr__(self, name):
110 '''Get an attribute or item by B{C{name}}.
111 '''
112 try:
113 return self[name]
114 except KeyError:
115 pass
116 name = _DOT_(self.__class__.__name__, name)
117 raise _AttributeError(item=name, txt=_doesn_t_exist_)
119 def __repr__(self):
120 '''Default C{repr(self)}.
121 '''
122 return self.toRepr()
124 def __str__(self):
125 '''Default C{str(self)}.
126 '''
127 return self.toStr()
129 @property_RO
130 def iteration(self): # see .named._NamedBase
131 '''Get the iteration number (C{int}) or
132 C{None} if not available/applicable.
133 '''
134 return self._iteration
136 def set_(self, iteration=None, **items): # PYCHOK signature
137 '''Add one or several new items or replace existing ones.
139 @kwarg iteration: Optional C{iteration} (C{int}).
140 @kwarg items: One or more C{name=value} pairs.
141 '''
142 if iteration is not None:
143 self._iteration = iteration
144 dict.update(self, items)
145 return self # in .rhumbBase.RhumbLineBase
147 def toRepr(self, **prec_fmt): # PYCHOK signature
148 '''Like C{repr(dict)} but with C{name} prefix and with
149 C{floats} formatted by function L{pygeodesy.fstr}.
150 '''
151 n = _xkwds_get(self, name=classname(self))
152 return Fmt.PAREN(n, self._toT(_EQUAL_, **prec_fmt))
154 def toStr(self, **prec_fmt): # PYCHOK signature
155 '''Like C{str(dict)} but with C{floats} formatted by
156 function L{pygeodesy.fstr}.
157 '''
158 return Fmt.CURLY(self._toT(_COLONSPACE_, **prec_fmt))
160 def _toT(self, sep, **kwds):
161 '''(INTERNAL) Helper for C{.toRepr} and C{.toStr}, also
162 in C{_NamedDict} below.
163 '''
164 kwds = _xkwds(kwds, prec=6, fmt=Fmt.F, sep=sep)
165 return _COMMASPACE_.join(pairs(itemsorted(self), **kwds))
168class _Named(object):
169 '''(INTERNAL) Root class for named objects.
170 '''
171 _iteration = None # iteration number (C{int}) or C{None}
172 _name = NN # name (C{str})
173 _classnaming = False # prefixed (C{bool})
174# _updates = 0 # OBSOLETE Property/property updates
176 def __imatmul__(self, other): # PYCHOK no cover
177 '''Not implemented.'''
178 return _NotImplemented(self, other) # PYCHOK Python 3.5+
180 def __matmul__(self, other): # PYCHOK no cover
181 '''Not implemented.'''
182 return _NotImplemented(self, other) # PYCHOK Python 3.5+
184 def __repr__(self):
185 '''Default C{repr(self)}.
186 '''
187 return Fmt.ANGLE(_SPACE_(self, _at_, hex(id(self))))
189 def __rmatmul__(self, other): # PYCHOK no cover
190 '''Not implemented.'''
191 return _NotImplemented(self, other) # PYCHOK Python 3.5+
193 def __str__(self):
194 '''Default C{str(self)}.
195 '''
196 return self.named2
198 def attrs(self, *names, **sep_COMMASPACE__Nones_True__pairs_kwds):
199 '''Join named attributes as I{name=value} strings, with C{float}s formatted by
200 function L{pygeodesy.fstr}.
202 @arg names: The attribute names, all positional (C{str}).
203 @kwarg sep_COMMASPACE__Nones_True__pairs_kwds: Keyword argument for function
204 L{pygeodesy.pairs}, except C{B{sep}=", "} and C{B{Nones}=True} to
205 in- or exclude missing or C{None}-valued attributes.
207 @return: All C{name=value} pairs, joined by B{C{sep}} (C{str}).
209 @see: Functions L{pygeodesy.attrs}, L{pygeodesy.fstr} and L{pygeodesy.pairs}.
210 '''
211 def _sep_kwds(sep=_COMMASPACE_, **kwds):
212 return sep, kwds
214 sep, kwds = _sep_kwds(**sep_COMMASPACE__Nones_True__pairs_kwds)
215 return sep.join(attrs(self, *names, **kwds))
217 @Property_RO
218 def classname(self):
219 '''Get this object's C{[module.]class} name (C{str}), see
220 property C{.classnaming} and function C{classnaming}.
221 '''
222 return classname(self, prefixed=self._classnaming)
224 @property_doc_(''' the class naming (C{bool}).''')
225 def classnaming(self):
226 '''Get the class naming (C{bool}), see function C{classnaming}.
227 '''
228 return self._classnaming
230 @classnaming.setter # PYCHOK setter!
231 def classnaming(self, prefixed):
232 '''Set the class naming for C{[module.].class} names (C{bool})
233 to C{True} to include the module name.
234 '''
235 b = bool(prefixed)
236 if self._classnaming != b:
237 self._classnaming = b
238 _update_attrs(self, *_Named_Property_ROs)
240 def classof(self, *args, **kwds):
241 '''Create another instance of this very class.
243 @arg args: Optional, positional arguments.
244 @kwarg kwds: Optional, keyword arguments.
246 @return: New instance (B{self.__class__}).
247 '''
248 return _xnamed(self.__class__(*args, **kwds), self.name)
250 def copy(self, deep=False, name=NN):
251 '''Make a shallow or deep copy of this instance.
253 @kwarg deep: If C{True} make a deep, otherwise
254 a shallow copy (C{bool}).
255 @kwarg name: Optional, non-empty name (C{str}).
257 @return: The copy (C{This class} or sub-class thereof).
258 '''
259 c = _xcopy(self, deep=deep)
260 if name:
261 c.rename(name)
262 return c
264 def _DOT_(self, *names):
265 '''(INTERNAL) Period-join C{self.name} and C{names}.
266 '''
267 return _DOT_(self.name, *names)
269 def dup(self, deep=False, **items):
270 '''Duplicate this instance, replacing some attributes.
272 @kwarg deep: If C{True} duplicate deep, otherwise shallow.
273 @kwarg items: Attributes to be changed (C{any}).
275 @return: The duplicate (C{This class} or sub-class thereof).
277 @raise AttributeError: Some B{C{items}} invalid.
278 '''
279 n = self.name
280 m = _xkwds_pop(items, name=n)
281 d = _xdup(self, deep=deep, **items)
282 if m != n:
283 d.rename(m)
284# if items:
285# _update_all(d)
286 return d
288 def _instr(self, name, prec, *attrs, **props_kwds):
289 '''(INTERNAL) Format, used by C{Conic}, C{Ellipsoid}, C{Transform}, C{Triaxial}.
290 '''
291 def _props_kwds(props=(), **kwds):
292 return props, kwds
294 t = Fmt.EQUAL(_name_, repr(name or self.name)),
295 if attrs:
296 t += pairs(((a, getattr(self, a)) for a in attrs),
297 prec=prec, ints=True)
298 props, kwds =_props_kwds(**props_kwds)
299 if props:
300 t += pairs(((p.name, getattr(self, p.name)) for p in props),
301 prec=prec, ints=True)
302 if kwds:
303 t += pairs(kwds, prec=prec)
304 return _COMMASPACE_.join(t[1:] if name is None else t)
306 @property_RO
307 def iteration(self): # see .karney.GDict
308 '''Get the most recent iteration number (C{int}) or C{None}
309 if not available or not applicable.
311 @note: The interation number may be an aggregate number over
312 several, nested functions.
313 '''
314 return self._iteration
316 def methodname(self, which):
317 '''Get a method C{[module.]class.method} name of this object (C{str}).
319 @arg which: The method (C{callable}).
320 '''
321 return _DOT_(self.classname, which.__name__ if callable(which) else _NN_)
323 @property_doc_(''' the name (C{str}).''')
324 def name(self):
325 '''Get the name (C{str}).
326 '''
327 return self._name
329 @name.setter # PYCHOK setter!
330 def name(self, name):
331 '''Set the name (C{str}).
333 @raise NameError: Can't rename, use method L{rename}.
334 '''
335 m, n = self._name, str(name)
336 if not m:
337 self._name = n
338 elif n != m:
339 n = repr(n)
340 c = self.classname
341 t = _DOT_(c, Fmt.PAREN(self.rename.__name__, n))
342 m = Fmt.PAREN(_SPACE_('was', repr(m)))
343 n = _DOT_(c, _EQUALSPACED_(_name_, n))
344 n = _SPACE_(n, m)
345 raise _NameError(_SPACE_('use', t), txt=_not_(n))
346 # to set the name from a sub-class, use
347 # self.name = name or
348 # _Named.name.fset(self, name), but NOT
349 # _Named(self).name = name
351 @Property_RO
352 def named(self):
353 '''Get the name I{or} class name or C{""} (C{str}).
354 '''
355 return self.name or self.classname
357 @Property_RO
358 def named2(self):
359 '''Get the C{class} name I{and/or} the name or C{""} (C{str}).
360 '''
361 return _xjoined_(self.classname, self.name)
363 @Property_RO
364 def named3(self):
365 '''Get the I{prefixed} C{class} name I{and/or} the name or C{""} (C{str}).
366 '''
367 return _xjoined_(classname(self, prefixed=True), self.name)
369 @Property_RO
370 def named4(self):
371 '''Get the C{package.module.class} name I{and/or} the name or C{""} (C{str}).
372 '''
373 return _xjoined_(_DOT_(self.__module__, self.__class__.__name__), self.name)
375 def rename(self, name):
376 '''Change the name.
378 @arg name: The new name (C{str}).
380 @return: The old name (C{str}).
381 '''
382 m, n = self._name, str(name)
383 if n != m:
384 self._name = n
385 _update_attrs(self, *_Named_Property_ROs)
386 return m
388 @property_RO
389 def sizeof(self):
390 '''Get the current size in C{bytes} of this instance (C{int}).
391 '''
392 return _sizeof(self)
394 def toRepr(self, **unused): # PYCHOK no cover
395 '''Default C{repr(self)}.
396 '''
397 return repr(self)
399 def toStr(self, **unused): # PYCHOK no cover
400 '''Default C{str(self)}.
401 '''
402 return str(self)
404 @deprecated_method
405 def toStr2(self, **kwds): # PYCHOK no cover
406 '''DEPRECATED on 23.10.07, use method C{toRepr}.'''
407 return self.toRepr(**kwds)
409 def _unstr(self, which, *args, **kwds):
410 '''(INTERNAL) Return the string representation of a method
411 invokation of this instance: C{str(self).method(...)}
413 @see: Function L{pygeodesy.unstr}.
414 '''
415 n = _DOT_(self, which.__name__ if callable(which) else _NN_)
416 return unstr(n, *args, **kwds)
418 def _xnamed(self, inst, name=NN, force=False):
419 '''(INTERNAL) Set the instance' C{.name = self.name}.
421 @arg inst: The instance (C{_Named}).
422 @kwarg name: Optional name, overriding C{self.name} (C{str}).
423 @kwarg force: Force name change (C{bool}).
425 @return: The B{C{inst}}, named if not named before.
426 '''
427 return _xnamed(inst, name or self.name, force=force)
429 def _xrenamed(self, inst):
430 '''(INTERNAL) Rename the instance' C{.name = self.name}.
432 @arg inst: The instance (C{_Named}).
434 @return: The B{C{inst}}, named if not named before.
436 @raise TypeError: Not C{isinstance(B{inst}, _Named)}.
437 '''
438 if not isinstance(inst, _Named):
439 raise _IsnotError(_valid_, inst=inst)
441 inst.rename(self.name)
442 return inst
444_Named_Property_ROs = _allPropertiesOf_n(5, _Named, Property_RO) # PYCHOK once
447class _NamedBase(_Named):
448 '''(INTERNAL) Base class with name.
449 '''
450 def __repr__(self):
451 '''Default C{repr(self)}.
452 '''
453 return self.toRepr()
455 def __str__(self):
456 '''Default C{str(self)}.
457 '''
458 return self.toStr()
460# def notImplemented(self, attr):
461# '''Raise error for a missing method, function or attribute.
462#
463# @arg attr: Attribute name (C{str}).
464#
465# @raise NotImplementedError: No such attribute.
466# '''
467# c = self.__class__.__name__
468# return NotImplementedError(_DOT_(c, attr))
470 def others(self, *other, **name_other_up):
471 '''Refined class comparison, invoked as C{.others(other)},
472 C{.others(name=other)} or C{.others(other, name='other')}.
474 @arg other: The other instance (any C{type}).
475 @kwarg name_other_up: Overriding C{name=other} and C{up=1}
476 keyword arguments.
478 @return: The B{C{other}} iff compatible with this instance's
479 C{class} or C{type}.
481 @raise TypeError: Mismatch of the B{C{other}} and this
482 instance's C{class} or C{type}.
483 '''
484 if other: # most common, just one arg B{C{other}}
485 other0 = other[0]
486 if isinstance(other0, self.__class__) or \
487 isinstance(self, other0.__class__):
488 return other0
490 other, name, up = _xother3(self, other, **name_other_up)
491 if isinstance(self, other.__class__) or \
492 isinstance(other, self.__class__):
493 return _xnamed(other, name)
495 raise _xotherError(self, other, name=name, up=up + 1)
497 def toRepr(self, **kwds): # PYCHOK expected
498 '''(INTERNAL) I{Could be overloaded}.
500 @kwarg kwds: Optional, C{toStr} keyword arguments.
502 @return: C{toStr}() with keyword arguments (as C{str}).
503 '''
504 t = lrstrip(self.toStr(**kwds))
505# if self.name:
506# t = NN(Fmt.EQUAL(name=repr(self.name)), sep, t)
507 return Fmt.PAREN(self.classname, t) # XXX (self.named, t)
509# def toRepr(self, **kwds)
510# if kwds:
511# s = NN.join(reprs((self,), **kwds))
512# else: # super().__repr__ only for Python 3+
513# s = super(self.__class__, self).__repr__()
514# return Fmt.PAREN(self.named, s) # clips(s)
516 def toStr(self, **kwds): # PYCHOK no cover
517 '''I{Must be overloaded}.'''
518 notOverloaded(self, **kwds)
520# def toStr(self, **kwds):
521# if kwds:
522# s = NN.join(strs((self,), **kwds))
523# else: # super().__str__ only for Python 3+
524# s = super(self.__class__, self).__str__()
525# return s
527 def _update(self, updated, *attrs, **setters):
528 '''(INTERNAL) Zap cached instance attributes and overwrite C{__dict__} or L{Property_RO} values.
529 '''
530 u = _update_all(self, *attrs) if updated else 0
531 if setters:
532 d = self.__dict__
533 # double-check that setters are Property_RO's
534 for n, v in setters.items():
535 if n in d or _hasProperty(self, n, Property_RO):
536 d[n] = v
537 else:
538 raise _AssertionError(n, v, txt=repr(self))
539 u += len(setters)
540 return u
543class _NamedDict(_Dict, _Named):
544 '''(INTERNAL) Named C{dict} with key I{and} attribute
545 access to the items.
546 '''
547 def __init__(self, *args, **kwds):
548 if args: # args override kwds
549 if len(args) != 1:
550 t = unstr(self.classname, *args, **kwds) # PYCHOK no cover
551 raise _ValueError(args=len(args), txt=t)
552 kwds = _xkwds(dict(args[0]), **kwds)
553 if _name_ in kwds:
554 _Named.name.fset(self, kwds.pop(_name_)) # see _Named.name
555 _Dict.__init__(self, kwds)
557 def __delattr__(self, name):
558 '''Delete an attribute or item by B{C{name}}.
559 '''
560 if name in _Dict.keys(self):
561 _Dict.pop(name)
562 elif name in (_name_, _name):
563 # _Dict.__setattr__(self, name, NN)
564 _Named.rename(self, NN)
565 else:
566 _Dict.__delattr__(self, name)
568 def __getattr__(self, name):
569 '''Get an attribute or item by B{C{name}}.
570 '''
571 try:
572 return self[name]
573 except KeyError:
574 if name == _name_:
575 return _Named.name.fget(self)
576 raise _AttributeError(item=self._DOT_(name), txt=_doesn_t_exist_)
578 def __getitem__(self, key):
579 '''Get the value of an item by B{C{key}}.
580 '''
581 if key == _name_:
582 raise KeyError(Fmt.SQUARE(self.classname, key))
583 return _Dict.__getitem__(self, key)
585 def __setattr__(self, name, value):
586 '''Set attribute or item B{C{name}} to B{C{value}}.
587 '''
588 if name in _Dict.keys(self):
589 _Dict.__setitem__(self, name, value) # self[name] = value
590 else:
591 _Dict.__setattr__(self, name, value)
593 def __setitem__(self, key, value):
594 '''Set item B{C{key}} to B{C{value}}.
595 '''
596 if key == _name_:
597 raise KeyError(_EQUAL_(Fmt.SQUARE(self.classname, key), repr(value)))
598 _Dict.__setitem__(self, key, value)
600 def toRepr(self, **prec_fmt): # PYCHOK signature
601 '''Like C{repr(dict)} but with C{name} prefix and with
602 C{floats} formatted by function L{pygeodesy.fstr}.
603 '''
604 return Fmt.PAREN(self.name, self._toT(_EQUAL_, **prec_fmt))
606 def toStr(self, **prec_fmt): # PYCHOK signature
607 '''Like C{str(dict)} but with C{floats} formatted by
608 function L{pygeodesy.fstr}.
609 '''
610 return Fmt.CURLY(self._toT(_COLONSPACE_, **prec_fmt))
613class _NamedEnum(_NamedDict):
614 '''(INTERNAL) Enum-like C{_NamedDict} with attribute access
615 restricted to valid keys.
616 '''
617 _item_Classes = ()
619 def __init__(self, Class, *Classes, **name):
620 '''New C{_NamedEnum}.
622 @arg Class: Initial class or type acceptable as items
623 values (C{type}).
624 @arg Classes: Additional, acceptable classes or C{type}s.
625 '''
626 self._item_Classes = (Class,) + Classes
627 n = _xkwds_get(name, name=NN) or NN(Class.__name__, _s_)
628 if n and _xvalid(n, _OK=True):
629 _Named.name.fset(self, n) # see _Named.name
631 def __getattr__(self, name):
632 '''Get the value of an attribute or item by B{C{name}}.
633 '''
634 try:
635 return self[name]
636 except KeyError:
637 if name == _name_:
638 return _NamedDict.name.fget(self)
639 raise _AttributeError(item=self._DOT_(name), txt=_doesn_t_exist_)
641 def __repr__(self):
642 '''Default C{repr(self)}.
643 '''
644 return self.toRepr()
646 def __str__(self):
647 '''Default C{str(self)}.
648 '''
649 return self.toStr()
651 def _assert(self, **kwds):
652 '''(INTERNAL) Check attribute name against given, registered name.
653 '''
654 pypy = _isPyPy()
655 for n, v in kwds.items():
656 if isinstance(v, _LazyNamedEnumItem): # property
657 assert (n == v.name) if pypy else (n is v.name)
658 # assert not hasattr(self.__class__, n)
659 setattr(self.__class__, n, v)
660 elif isinstance(v, self._item_Classes): # PYCHOK no cover
661 assert self[n] is v and getattr(self, n) \
662 and self.find(v) == n
663 else:
664 raise _TypeError(v, name=n)
666 def find(self, item, dflt=None):
667 '''Find a registered item.
669 @arg item: The item to look for (any C{type}).
670 @kwarg dflt: Value to return if not found (any C{type}).
672 @return: The B{C{item}}'s name if found (C{str}), or C{{dflt}} if
673 there is no such I{registered} B{C{item}}.
674 '''
675 for k, v in self.items(): # or _Dict.items(self)
676 if v is item:
677 return k
678 return dflt
680 def get(self, name, dflt=None):
681 '''Get the value of a I{registered} item.
683 @arg name: The name of the item (C{str}).
684 @kwarg dflt: Value to return (any C{type}).
686 @return: The item with B{C{name}} if found, or B{C{dflt}} if
687 there is no item I{registered} with that B{C{name}}.
688 '''
689 # getattr needed to instantiate L{_LazyNamedEnumItem}
690 return getattr(self, name, dflt)
692 def items(self, all=False, asorted=False):
693 '''Yield all or only the I{registered} items.
695 @kwarg all: Use C{True} to yield {all} items or C{False}
696 for only the currently I{registered} ones.
697 @kwarg asorted: If C{True}, yield the items sorted in
698 I{alphabetical, case-insensitive} order.
699 '''
700 if all: # instantiate any remaining L{_LazyNamedEnumItem} ...
701 # ... and remove the L{_LazyNamedEnumItem} from the class
702 for n in tuple(n for n, p in self.__class__.__dict__.items()
703 if isinstance(p, _LazyNamedEnumItem)):
704 _ = getattr(self, n)
705 return itemsorted(self) if asorted else _Dict.items(self)
707 def keys(self, **all_asorted):
708 '''Yield the keys (C{str}) of all or only the I{registered} items,
709 optionally sorted I{alphabetically} and I{case-insensitively}.
711 @kwarg all_asorted: See method C{items}..
712 '''
713 for k, _ in self.items(**all_asorted):
714 yield k
716 def popitem(self):
717 '''Remove I{an, any} curretly I{registed} item.
719 @return: The removed item.
720 '''
721 return self._zapitem(*_Dict.pop(self))
723 def register(self, item):
724 '''Registed a new item.
726 @arg item: The item (any C{type}).
728 @return: The item name (C{str}).
730 @raise NameError: An B{C{item}} already registered with
731 that name or the B{C{item}} has no, an
732 empty or an invalid name.
734 @raise TypeError: The B{C{item}} type invalid.
735 '''
736 try:
737 n = item.name
738 if not (n and isstr(n) and isidentifier(n)):
739 raise ValueError
740 except (AttributeError, ValueError, TypeError) as x:
741 raise _NameError(_DOT_(_item_, _name_), item, cause=x)
742 if n in self:
743 raise _NameError(self._DOT_(n), item, txt=_exists_)
744 if not (self._item_Classes and isinstance(item, self._item_Classes)):
745 raise _TypesError(self._DOT_(n), item, *self._item_Classes)
746 self[n] = item
748 def unregister(self, name_or_item):
749 '''Remove a I{registered} item.
751 @arg name_or_item: Name (C{str}) or the item (any C{type}).
753 @return: The unregistered item.
755 @raise NameError: No item with that B{C{name}}.
757 @raise ValueError: No such item.
758 '''
759 if isstr(name_or_item):
760 name = name_or_item
761 else:
762 name = self.find(name_or_item)
763 try:
764 item = _Dict.pop(self, name)
765 except KeyError:
766 raise _NameError(item=self._DOT_(name), txt=_doesn_t_exist_)
767 return self._zapitem(name, item)
769 pop = unregister
771 def toRepr(self, prec=6, fmt=Fmt.F, sep=_COMMANL_, **all_asorted): # PYCHOK _NamedDict
772 '''Like C{repr(dict)} but C{name}s optionally sorted and
773 C{floats} formatted by function L{pygeodesy.fstr}.
774 '''
775 t = ((self._DOT_(n), v) for n, v in self.items(**all_asorted))
776 return sep.join(pairs(t, prec=prec, fmt=fmt, sep=_COLONSPACE_))
778 def toStr(self, *unused, **all_asorted): # PYCHOK _NamedDict
779 '''Return a string with all C{name}s, optionally sorted.
780 '''
781 return self._DOT_(_COMMASPACEDOT_.join(self.keys(**all_asorted)))
783 def values(self, **all_asorted):
784 '''Yield the value (C{type}) of all or only the I{registered} items,
785 optionally sorted I{alphabetically} and I{case-insensitively}.
787 @kwarg all_asorted: See method C{items}.
788 '''
789 for _, v in self.items(**all_asorted):
790 yield v
792 def _zapitem(self, name, item):
793 # remove _LazyNamedEnumItem property value if still present
794 if self.__dict__.get(name, None) is item:
795 self.__dict__.pop(name) # [name] = None
796 item._enum = None
797 return item
800class _LazyNamedEnumItem(property_RO): # XXX or descriptor?
801 '''(INTERNAL) Lazily instantiated L{_NamedEnumItem}.
802 '''
803 pass
806def _lazyNamedEnumItem(name, *args, **kwds):
807 '''(INTERNAL) L{_LazyNamedEnumItem} property-like factory.
809 @see: Luciano Ramalho, "Fluent Python", O'Reilly, Example
810 19-24, 2016 p. 636 or Example 22-28, 2022 p. 869+
811 '''
812 def _fget(inst):
813 # assert isinstance(inst, _NamedEnum)
814 try: # get the item from the instance' __dict__
815 # item = inst.__dict__[name] # ... or _Dict
816 item = inst[name]
817 except KeyError:
818 # instantiate an _NamedEnumItem, it self-registers
819 item = inst._Lazy(*args, **_xkwds(kwds, name=name))
820 # assert inst[name] is item # MUST be registered
821 # store the item in the instance' __dict__ ...
822 # inst.__dict__[name] = item # ... or update the
823 inst.update({name: item}) # ... _Dict for Triaxials
824 # remove the property from the registry class, such that
825 # (a) the property no longer overrides the instance' item
826 # in inst.__dict__ and (b) _NamedEnum.items(all=True) only
827 # sees any un-instantiated ones yet to be instantiated
828 p = getattr(inst.__class__, name, None)
829 if isinstance(p, _LazyNamedEnumItem):
830 delattr(inst.__class__, name)
831 # assert isinstance(item, _NamedEnumItem)
832 return item
834 p = _LazyNamedEnumItem(_fget)
835 p.name = name
836 return p
839class _NamedEnumItem(_NamedBase):
840 '''(INTERNAL) Base class for items in a C{_NamedEnum} registery.
841 '''
842 _enum = None
844# def __ne__(self, other): # XXX fails for Lcc.conic = conic!
845# '''Compare this and an other item.
846#
847# @return: C{True} if different, C{False} otherwise.
848# '''
849# return not self.__eq__(other)
851 @property_doc_(''' the I{registered} name (C{str}).''')
852 def name(self):
853 '''Get the I{registered} name (C{str}).
854 '''
855 return self._name
857 @name.setter # PYCHOK setter!
858 def name(self, name):
859 '''Set the name, unless already registered (C{str}).
860 '''
861 if self._enum:
862 raise _NameError(str(name), self, txt=_registered_) # XXX _TypeError
863 self._name = str(name)
865 def _register(self, enum, name):
866 '''(INTERNAL) Add this item as B{C{enum.name}}.
868 @note: Don't register if name is empty or doesn't
869 start with a letter.
870 '''
871 if name and _xvalid(name, _OK=True):
872 self.name = name
873 if name[:1].isalpha(): # '_...' not registered
874 enum.register(self)
875 self._enum = enum
877 def unregister(self):
878 '''Remove this instance from its C{_NamedEnum} registry.
880 @raise AssertionError: Mismatch of this and registered item.
882 @raise NameError: This item is unregistered.
883 '''
884 enum = self._enum
885 if enum and self.name and self.name in enum:
886 item = enum.unregister(self.name)
887 if item is not self:
888 t = _SPACE_(repr(item), _vs_, repr(self)) # PYCHOK no cover
889 raise _AssertionError(t)
892class _NamedTuple(tuple, _Named):
893 '''(INTERNAL) Base for named C{tuple}s with both index I{and}
894 attribute name access to the items.
896 @note: This class is similar to Python's C{namedtuple},
897 but statically defined, lighter and limited.
898 '''
899 _Names_ = () # item names, non-identifier, no leading underscore
900 '''Tuple specifying the C{name} of each C{Named-Tuple} item.
902 @note: Specify at least 2 item names.
903 '''
904 _Units_ = () # .units classes
905 '''Tuple defining the C{units} of the value of each C{Named-Tuple} item.
907 @note: The C{len(_Units_)} must match C{len(_Names_)}.
908 '''
909 _validated = False # set to True I{per sub-class!}
911 def __new__(cls, arg, *args, **iteration_name):
912 '''New L{_NamedTuple} initialized with B{C{positional}} arguments.
914 @arg arg: Tuple items (C{tuple}, C{list}, ...) or first tuple
915 item of several more in other positional arguments.
916 @arg args: Tuple items (C{any}), all positional arguments.
917 @kwarg iteration_name: Only keyword arguments C{B{iteration}=None}
918 and C{B{name}=NN} are used, any other are
919 I{silently} ignored.
921 @raise LenError: Unequal number of positional arguments and
922 number of item C{_Names_} or C{_Units_}.
924 @raise TypeError: The C{_Names_} or C{_Units_} attribute is
925 not a C{tuple} of at least 2 items.
927 @raise ValueError: Item name is not a C{str} or valid C{identifier}
928 or starts with C{underscore}.
929 '''
930 n, args = len2(((arg,) + args) if args else arg)
931 self = tuple.__new__(cls, args)
932 if not self._validated:
933 self._validate()
935 N = len(self._Names_)
936 if n != N:
937 raise LenError(self.__class__, args=n, _Names_=N)
939 if iteration_name:
940 self._kwdself(**iteration_name)
941 return self
943 def __delattr__(self, name):
944 '''Delete an attribute by B{C{name}}.
946 @note: Items can not be deleted.
947 '''
948 if name in self._Names_:
949 raise _TypeError(_del_, _DOT_(self.classname, name), txt=_immutable_)
950 elif name in (_name_, _name):
951 _Named.__setattr__(self, name, NN) # XXX _Named.name.fset(self, NN)
952 else:
953 tuple.__delattr__(self, name)
955 def __getattr__(self, name):
956 '''Get the value of an attribute or item by B{C{name}}.
957 '''
958 try:
959 return tuple.__getitem__(self, self._Names_.index(name))
960 except IndexError:
961 raise _IndexError(_DOT_(self.classname, Fmt.ANGLE(_name_)), name)
962 except ValueError: # e.g. _iteration
963 return tuple.__getattribute__(self, name)
965# def __getitem__(self, index): # index, slice, etc.
966# '''Get the item(s) at an B{C{index}} or slice.
967# '''
968# return tuple.__getitem__(self, index)
970 def __repr__(self):
971 '''Default C{repr(self)}.
972 '''
973 return self.toRepr()
975 def __setattr__(self, name, value):
976 '''Set attribute or item B{C{name}} to B{C{value}}.
977 '''
978 if name in self._Names_:
979 raise _TypeError(_DOT_(self.classname, name), value, txt=_immutable_)
980 elif name in (_name_, _name):
981 _Named.__setattr__(self, name, value) # XXX _Named.name.fset(self, value)
982 else: # e.g. _iteration
983 tuple.__setattr__(self, name, value)
985 def __str__(self):
986 '''Default C{repr(self)}.
987 '''
988 return self.toStr()
990 def dup(self, name=NN, **items):
991 '''Duplicate this tuple replacing one or more items.
993 @kwarg name: Optional new name (C{str}).
994 @kwarg items: Items to be replaced (C{name=value} pairs), if any.
996 @return: A copy of this tuple with B{C{items}}.
998 @raise NameError: Some B{C{items}} invalid.
999 '''
1000 tl = list(self)
1001 if items:
1002 _ix = self._Names_.index
1003 try:
1004 for n, v in items.items():
1005 tl[_ix(n)] = v
1006 except ValueError: # bad item name
1007 raise _NameError(_DOT_(self.classname, n), v, this=self)
1008 return self.classof(*tl, name=name or self.name)
1010 def items(self):
1011 '''Yield the items, each as a C{(name, value)} pair (C{2-tuple}).
1013 @see: Method C{.units}.
1014 '''
1015 for n, v in _zip(self._Names_, self): # strict=True
1016 yield n, v
1018 iteritems = items
1020 def _kwdself(self, iteration=None, name=NN, **unused):
1021 '''(INTERNAL) Set C{__new__} keyword arguments.
1022 '''
1023 if iteration is not None:
1024 self._iteration = iteration
1025 if name:
1026 self.name = name
1028 def toRepr(self, prec=6, sep=_COMMASPACE_, fmt=Fmt.F, **unused): # PYCHOK signature
1029 '''Return this C{Named-Tuple} items as C{name=value} string(s).
1031 @kwarg prec: The C{float} precision, number of decimal digits (0..9).
1032 Trailing zero decimals are stripped for B{C{prec}} values
1033 of 1 and above, but kept for negative B{C{prec}} values.
1034 @kwarg sep: Separator to join (C{str}).
1035 @kwarg fmt: Optional, C{float} format (C{str}).
1037 @return: Tuple items (C{str}).
1038 '''
1039 t = pairs(self.items(), prec=prec, fmt=fmt)
1040# if self.name:
1041# t = (Fmt.EQUAL(name=repr(self.name)),) + t
1042 return Fmt.PAREN(self.named, sep.join(t)) # XXX (self.classname, sep.join(t))
1044 def toStr(self, prec=6, sep=_COMMASPACE_, fmt=Fmt.F, **unused): # PYCHOK signature
1045 '''Return this C{Named-Tuple} items as string(s).
1047 @kwarg prec: The C{float} precision, number of decimal digits (0..9).
1048 Trailing zero decimals are stripped for B{C{prec}} values
1049 of 1 and above, but kept for negative B{C{prec}} values.
1050 @kwarg sep: Separator to join (C{str}).
1051 @kwarg fmt: Optional C{float} format (C{str}).
1053 @return: Tuple items (C{str}).
1054 '''
1055 return Fmt.PAREN(sep.join(reprs(self, prec=prec, fmt=fmt)))
1057 def toUnits(self, Error=UnitError): # overloaded in .frechet, .hausdorff
1058 '''Return a copy of this C{Named-Tuple} with each item value wrapped
1059 as an instance of its L{units} class.
1061 @kwarg Error: Error to raise for L{units} issues (C{UnitError}).
1063 @return: A duplicate of this C{Named-Tuple} (C{C{Named-Tuple}}).
1065 @raise Error: Invalid C{Named-Tuple} item or L{units} class.
1066 '''
1067 t = (v for _, v in self.units(Error=Error))
1068 return self.classof(*tuple(t))
1070 def units(self, Error=UnitError):
1071 '''Yield the items, each as a C{(name, value}) pair (C{2-tuple}) with
1072 the value wrapped as an instance of its L{units} class.
1074 @kwarg Error: Error to raise for L{units} issues (C{UnitError}).
1076 @raise Error: Invalid C{Named-Tuple} item or L{units} class.
1078 @see: Method C{.items}.
1079 '''
1080 for n, v, U in _zip(self._Names_, self, self._Units_): # strict=True
1081 if not (v is None or U is None
1082 or (isclass(U) and
1083 isinstance(v, U) and
1084 hasattr(v, _name_) and
1085 v.name == n)): # PYCHOK indent
1086 v = U(v, name=n, Error=Error)
1087 yield n, v
1089 iterunits = units
1091 def _validate(self, _OK=False): # see .EcefMatrix
1092 '''(INTERNAL) One-time check of C{_Names_} and C{_Units_}
1093 for each C{_NamedUnit} I{sub-class separately}.
1094 '''
1095 ns = self._Names_
1096 if not (isinstance(ns, tuple) and len(ns) > 1): # XXX > 0
1097 raise _TypeError(_DOT_(self.classname, _Names_), ns)
1098 for i, n in enumerate(ns):
1099 if not _xvalid(n, _OK=_OK):
1100 t = Fmt.SQUARE(_Names_=i) # PYCHOK no cover
1101 raise _ValueError(_DOT_(self.classname, t), n)
1103 us = self._Units_
1104 if not isinstance(us, tuple):
1105 raise _TypeError(_DOT_(self.classname, _Units_), us)
1106 if len(us) != len(ns):
1107 raise LenError(self.__class__, _Units_=len(us), _Names_=len(ns))
1108 for i, u in enumerate(us):
1109 if not (u is None or callable(u)):
1110 t = Fmt.SQUARE(_Units_=i) # PYCHOK no cover
1111 raise _TypeError(_DOT_(self.classname, t), u)
1113 self.__class__._validated = True
1115 def _xtend(self, xTuple, *items, **name):
1116 '''(INTERNAL) Extend this C{Named-Tuple} with C{items} to an other B{C{xTuple}}.
1117 '''
1118 if (issubclassof(xTuple, _NamedTuple) and
1119 (len(self._Names_) + len(items)) == len(xTuple._Names_) and
1120 self._Names_ == xTuple._Names_[:len(self)]):
1121 return xTuple(self + items, **_xkwds(name, name=self.name)) # *(self + items)
1122 c = NN(self.classname, repr(self._Names_)) # PYCHOK no cover
1123 x = NN(xTuple.__name__, repr(xTuple._Names_)) # PYCHOK no cover
1124 raise TypeError(_SPACE_(c, _vs_, x))
1127def callername(up=1, dflt=NN, source=False, underOK=False):
1128 '''Get the name of the invoking callable.
1130 @kwarg up: Number of call stack frames up (C{int}).
1131 @kwarg dflt: Default return value (C{any}).
1132 @kwarg source: Include source file name and line number (C{bool}).
1133 @kwarg underOK: If C{True}, private, internal callables are OK,
1134 otherwise private callables are skipped (C{bool}).
1136 @return: The callable name (C{str}) or B{C{dflt}} if none found.
1137 '''
1138 try: # see .lazily._caller3
1139 for u in range(up, up + 32):
1140 n, f, s = _caller3(u)
1141 if n and (underOK or n.startswith(_DUNDER_) or
1142 not n.startswith(_UNDER_)):
1143 if source:
1144 n = NN(n, _AT_, f, _COLON_, str(s))
1145 return n
1146 except (AttributeError, ValueError):
1147 pass
1148 return dflt
1151def _callername2(args, callername=NN, source=False, underOK=False, up=2, **kwds):
1152 '''(INTERNAL) Extract C{callername}, C{source}, C{underOK} and C{up} from C{kwds}.
1153 '''
1154 n = callername or _MODS.named.callername(up=up + 1, source=source,
1155 underOK=underOK or bool(args or kwds))
1156 return n, kwds
1159def _callname(name, class_name, self_name, up=1):
1160 '''(INTERNAL) Assemble the name for an invokation.
1161 '''
1162 n, c = class_name, callername(up=up + 1)
1163 if c:
1164 n = _DOT_(n, Fmt.PAREN(c, name))
1165 if self_name:
1166 n = _SPACE_(n, repr(self_name))
1167 return n
1170def classname(inst, prefixed=None):
1171 '''Return the instance' class name optionally prefixed with the
1172 module name.
1174 @arg inst: The object (any C{type}).
1175 @kwarg prefixed: Include the module name (C{bool}), see
1176 function C{classnaming}.
1178 @return: The B{C{inst}}'s C{[module.]class} name (C{str}).
1179 '''
1180 if prefixed is None:
1181 prefixed = getattr(inst, classnaming.__name__, prefixed)
1182 return modulename(inst.__class__, prefixed=prefixed)
1185def classnaming(prefixed=None):
1186 '''Get/set the default class naming for C{[module.]class} names.
1188 @kwarg prefixed: Include the module name (C{bool}).
1190 @return: Previous class naming setting (C{bool}).
1191 '''
1192 t = _Named._classnaming
1193 if prefixed in (True, False):
1194 _Named._classnaming = prefixed
1195 return t
1198def modulename(clas, prefixed=None): # in .basics._xversion
1199 '''Return the class name optionally prefixed with the
1200 module name.
1202 @arg clas: The class (any C{class}).
1203 @kwarg prefixed: Include the module name (C{bool}), see
1204 function C{classnaming}.
1206 @return: The B{C{class}}'s C{[module.]class} name (C{str}).
1207 '''
1208 try:
1209 n = clas.__name__
1210 except AttributeError:
1211 n = '__name__' # _DUNDER_(NN, _name_, NN)
1212 if prefixed or (classnaming() if prefixed is None else False):
1213 try:
1214 m = clas.__module__.rsplit(_DOT_, 1)
1215 n = _DOT_.join(m[1:] + [n])
1216 except AttributeError:
1217 pass
1218 return n
1221def nameof(inst):
1222 '''Get the name of an instance.
1224 @arg inst: The object (any C{type}).
1226 @return: The instance' name (C{str}) or C{""}.
1227 '''
1228 n = _xattr(inst, name=NN)
1229 if not n: # and isinstance(inst, property):
1230 try:
1231 n = inst.fget.__name__
1232 except AttributeError:
1233 n = NN
1234 return n
1237def _notDecaps(where):
1238 '''De-Capitalize C{where.__name__}.
1239 '''
1240 n = where.__name__
1241 c = n[3].lower() # len(_not_)
1242 return NN(n[:3], _SPACE_, c, n[4:])
1245def _notError(inst, name, args, kwds): # PYCHOK no cover
1246 '''(INTERNAL) Format an error message.
1247 '''
1248 n = _DOT_(classname(inst, prefixed=True), _dunder_nameof(name, name))
1249 m = _COMMASPACE_.join(modulename(c, prefixed=True) for c in inst.__class__.__mro__[1:-1])
1250 return _COMMASPACE_(unstr(n, *args, **kwds), Fmt.PAREN(_MRO_, m))
1253def _NotImplemented(inst, *other, **kwds):
1254 '''(INTERNAL) Raise a C{__special__} error or return C{NotImplemented},
1255 but only if env variable C{PYGEODESY_NOTIMPLEMENTED=std}.
1256 '''
1257 if _std_NotImplemented:
1258 return NotImplemented
1259 n, kwds = _callername2(other, **kwds) # source=True
1260 t = unstr(_DOT_(classname(inst), n), *other, **kwds)
1261 raise _NotImplementedError(t, txt=repr(inst))
1264def notImplemented(inst, *args, **kwds): # PYCHOK no cover
1265 '''Raise a C{NotImplementedError} for a missing instance method or
1266 property or for a missing caller feature.
1268 @arg inst: Instance (C{any}) or C{None} for caller.
1269 @arg args: Method or property positional arguments (any C{type}s).
1270 @arg kwds: Method or property keyword arguments (any C{type}s),
1271 except C{B{callername}=NN}, C{B{underOK}=False} and
1272 C{B{up}=2}.
1273 '''
1274 n, kwds = _callername2(args, **kwds)
1275 t = _notError(inst, n, args, kwds) if inst else unstr(n, *args, **kwds)
1276 raise _NotImplementedError(t, txt=_notDecaps(notImplemented))
1279def notOverloaded(inst, *args, **kwds): # PYCHOK no cover
1280 '''Raise an C{AssertionError} for a method or property not overloaded.
1282 @arg inst: Instance (C{any}).
1283 @arg args: Method or property positional arguments (any C{type}s).
1284 @arg kwds: Method or property keyword arguments (any C{type}s),
1285 except C{B{callername}=NN}, C{B{underOK}=False} and
1286 C{B{up}=2}.
1287 '''
1288 n, kwds = _callername2(args, **kwds)
1289 t = _notError(inst, n, args, kwds)
1290 raise _AssertionError(t, txt=_notDecaps(notOverloaded))
1293def _Pass(arg, **unused): # PYCHOK no cover
1294 '''(INTERNAL) I{Pass-thru} class for C{_NamedTuple._Units_}.
1295 '''
1296 return arg
1299__all__ += _ALL_DOCS(_Named,
1300 _NamedBase, # _NamedDict,
1301 _NamedEnum, _NamedEnumItem,
1302 _NamedTuple)
1304# **) MIT License
1305#
1306# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
1307#
1308# Permission is hereby granted, free of charge, to any person obtaining a
1309# copy of this software and associated documentation files (the "Software"),
1310# to deal in the Software without restriction, including without limitation
1311# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1312# and/or sell copies of the Software, and to permit persons to whom the
1313# Software is furnished to do so, subject to the following conditions:
1314#
1315# The above copyright notice and this permission notice shall be included
1316# in all copies or substantial portions of the Software.
1317#
1318# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1319# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1320# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1321# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1322# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1323# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1324# OTHER DEALINGS IN THE SOFTWARE.