Coverage for pygeodesy/named.py: 96%
445 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-10-11 16:04 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2023-10-11 16:04 -0400
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.10.08'
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 def __getattr__(self, name):
108 '''Get an attribute or item by B{C{name}}.
109 '''
110 try:
111 return self[name]
112 except KeyError:
113 pass
114 name = _DOT_(self.__class__.__name__, name)
115 raise _AttributeError(item=name, txt=_doesn_t_exist_)
117 def __repr__(self):
118 '''Default C{repr(self)}.
119 '''
120 return self.toRepr()
122 def __str__(self):
123 '''Default C{str(self)}.
124 '''
125 return self.toStr()
127 def set_(self, **items): # PYCHOK signature
128 '''Add one or several new items or replace existing ones.
130 @kwarg items: One or more C{name=value} pairs.
131 '''
132 dict.update(self, items)
133 return self # in .rhumbBase.RhumbLineBase
135 def toRepr(self, **prec_fmt): # PYCHOK signature
136 '''Like C{repr(dict)} but with C{name} prefix and with
137 C{floats} formatted by function L{pygeodesy.fstr}.
138 '''
139 n = _xkwds_get(self, name=classname(self))
140 return Fmt.PAREN(n, self._toT(_EQUAL_, **prec_fmt))
142 def toStr(self, **prec_fmt): # PYCHOK signature
143 '''Like C{str(dict)} but with C{floats} formatted by
144 function L{pygeodesy.fstr}.
145 '''
146 return Fmt.CURLY(self._toT(_COLONSPACE_, **prec_fmt))
148 def _toT(self, sep, **kwds):
149 '''(INTERNAL) Helper for C{.toRepr} and C{.toStr}, also
150 in C{_NamedDict} below.
151 '''
152 kwds = _xkwds(kwds, prec=6, fmt=Fmt.F, sep=sep)
153 return _COMMASPACE_.join(pairs(itemsorted(self), **kwds))
156class _Named(object):
157 '''(INTERNAL) Root class for named objects.
158 '''
159 _iteration = None # iteration number (C{int}) or C{None}
160 _name = NN # name (C{str})
161 _classnaming = False # prefixed (C{bool})
162# _updates = 0 # OBSOLETE Property/property updates
164 def __imatmul__(self, other): # PYCHOK no cover
165 '''Not implemented.'''
166 return _NotImplemented(self, other) # PYCHOK Python 3.5+
168 def __matmul__(self, other): # PYCHOK no cover
169 '''Not implemented.'''
170 return _NotImplemented(self, other) # PYCHOK Python 3.5+
172 def __repr__(self):
173 '''Default C{repr(self)}.
174 '''
175 return Fmt.ANGLE(_SPACE_(self, _at_, hex(id(self))))
177 def __rmatmul__(self, other): # PYCHOK no cover
178 '''Not implemented.'''
179 return _NotImplemented(self, other) # PYCHOK Python 3.5+
181 def __str__(self):
182 '''Default C{str(self)}.
183 '''
184 return self.named2
186 def attrs(self, *names, **sep_COMMASPACE__Nones_True__pairs_kwds):
187 '''Join named attributes as I{name=value} strings, with C{float}s formatted by
188 function L{pygeodesy.fstr}.
190 @arg names: The attribute names, all positional (C{str}).
191 @kwarg sep_COMMASPACE__Nones_True__pairs_kwds: Keyword argument for function
192 L{pygeodesy.pairs}, except C{B{sep}=", "} and C{B{Nones}=True} to
193 in- or exclude missing or C{None}-valued attributes.
195 @return: All C{name=value} pairs, joined by B{C{sep}} (C{str}).
197 @see: Functions L{pygeodesy.attrs}, L{pygeodesy.fstr} and L{pygeodesy.pairs}.
198 '''
199 def _sep_kwds(sep=_COMMASPACE_, **kwds):
200 return sep, kwds
202 sep, kwds = _sep_kwds(**sep_COMMASPACE__Nones_True__pairs_kwds)
203 return sep.join(attrs(self, *names, **kwds))
205 @Property_RO
206 def classname(self):
207 '''Get this object's C{[module.]class} name (C{str}), see
208 property C{.classnaming} and function C{classnaming}.
209 '''
210 return classname(self, prefixed=self._classnaming)
212 @property_doc_(''' the class naming (C{bool}).''')
213 def classnaming(self):
214 '''Get the class naming (C{bool}), see function C{classnaming}.
215 '''
216 return self._classnaming
218 @classnaming.setter # PYCHOK setter!
219 def classnaming(self, prefixed):
220 '''Set the class naming for C{[module.].class} names (C{bool})
221 to C{True} to include the module name.
222 '''
223 b = bool(prefixed)
224 if self._classnaming != b:
225 self._classnaming = b
226 _update_attrs(self, *_Named_Property_ROs)
228 def classof(self, *args, **kwds):
229 '''Create another instance of this very class.
231 @arg args: Optional, positional arguments.
232 @kwarg kwds: Optional, keyword arguments.
234 @return: New instance (B{self.__class__}).
235 '''
236 return _xnamed(self.__class__(*args, **kwds), self.name)
238 def copy(self, deep=False, name=NN):
239 '''Make a shallow or deep copy of this instance.
241 @kwarg deep: If C{True} make a deep, otherwise
242 a shallow copy (C{bool}).
243 @kwarg name: Optional, non-empty name (C{str}).
245 @return: The copy (C{This class} or sub-class thereof).
246 '''
247 c = _xcopy(self, deep=deep)
248 if name:
249 c.rename(name)
250 return c
252 def _DOT_(self, *names):
253 '''(INTERNAL) Period-join C{self.name} and C{names}.
254 '''
255 return _DOT_(self.name, *names)
257 def dup(self, deep=False, **items):
258 '''Duplicate this instance, replacing some attributes.
260 @kwarg deep: If C{True} duplicate deep, otherwise shallow.
261 @kwarg items: Attributes to be changed (C{any}).
263 @return: The duplicate (C{This class} or sub-class thereof).
265 @raise AttributeError: Some B{C{items}} invalid.
266 '''
267 n = self.name
268 m = _xkwds_pop(items, name=n)
269 d = _xdup(self, deep=deep, **items)
270 if m != n:
271 d.rename(m)
272# if items:
273# _update_all(d)
274 return d
276 def _instr(self, name, prec, *attrs, **props_kwds):
277 '''(INTERNAL) Format, used by C{Conic}, C{Ellipsoid}, C{Transform}, C{Triaxial}.
278 '''
279 def _props_kwds(props=(), **kwds):
280 return props, kwds
282 t = Fmt.EQUAL(_name_, repr(name or self.name)),
283 if attrs:
284 t += pairs(((a, getattr(self, a)) for a in attrs),
285 prec=prec, ints=True)
286 props, kwds =_props_kwds(**props_kwds)
287 if props:
288 t += pairs(((p.name, getattr(self, p.name)) for p in props),
289 prec=prec, ints=True)
290 if kwds:
291 t += pairs(kwds, prec=prec)
292 return _COMMASPACE_.join(t[1:] if name is None else t)
294 @property_RO
295 def iteration(self): # see .karney.GDict
296 '''Get the most recent iteration number (C{int}) or C{None}
297 if not available or not applicable.
299 @note: The interation number may be an aggregate number over
300 several, nested functions.
301 '''
302 return self._iteration
304 def methodname(self, which):
305 '''Get a method C{[module.]class.method} name of this object (C{str}).
307 @arg which: The method (C{callable}).
308 '''
309 return _DOT_(self.classname, which.__name__ if callable(which) else _NN_)
311 @property_doc_(''' the name (C{str}).''')
312 def name(self):
313 '''Get the name (C{str}).
314 '''
315 return self._name
317 @name.setter # PYCHOK setter!
318 def name(self, name):
319 '''Set the name (C{str}).
321 @raise NameError: Can't rename, use method L{rename}.
322 '''
323 m, n = self._name, str(name)
324 if not m:
325 self._name = n
326 elif n != m:
327 n = repr(n)
328 c = self.classname
329 t = _DOT_(c, Fmt.PAREN(self.rename.__name__, n))
330 m = Fmt.PAREN(_SPACE_('was', repr(m)))
331 n = _DOT_(c, _EQUALSPACED_(_name_, n))
332 n = _SPACE_(n, m)
333 raise _NameError(_SPACE_('use', t), txt=_not_(n))
334 # to set the name from a sub-class, use
335 # self.name = name or
336 # _Named.name.fset(self, name), but NOT
337 # _Named(self).name = name
339 @Property_RO
340 def named(self):
341 '''Get the name I{or} class name or C{""} (C{str}).
342 '''
343 return self.name or self.classname
345 @Property_RO
346 def named2(self):
347 '''Get the C{class} name I{and/or} the name or C{""} (C{str}).
348 '''
349 return _xjoined_(self.classname, self.name)
351 @Property_RO
352 def named3(self):
353 '''Get the I{prefixed} C{class} name I{and/or} the name or C{""} (C{str}).
354 '''
355 return _xjoined_(classname(self, prefixed=True), self.name)
357 @Property_RO
358 def named4(self):
359 '''Get the C{package.module.class} name I{and/or} the name or C{""} (C{str}).
360 '''
361 return _xjoined_(_DOT_(self.__module__, self.__class__.__name__), self.name)
363 def rename(self, name):
364 '''Change the name.
366 @arg name: The new name (C{str}).
368 @return: The old name (C{str}).
369 '''
370 m, n = self._name, str(name)
371 if n != m:
372 self._name = n
373 _update_attrs(self, *_Named_Property_ROs)
374 return m
376 @property_RO
377 def sizeof(self):
378 '''Get the current size in C{bytes} of this instance (C{int}).
379 '''
380 return _sizeof(self)
382 def toRepr(self, **unused): # PYCHOK no cover
383 '''Default C{repr(self)}.
384 '''
385 return repr(self)
387 def toStr(self, **unused): # PYCHOK no cover
388 '''Default C{str(self)}.
389 '''
390 return str(self)
392 @deprecated_method
393 def toStr2(self, **kwds): # PYCHOK no cover
394 '''DEPRECATED on 23.10.07, use method C{toRepr}.'''
395 return self.toRepr(**kwds)
397 def _unstr(self, which, *args, **kwds):
398 '''(INTERNAL) Return the string representation of a method
399 invokation of this instance: C{str(self).method(...)}
401 @see: Function L{pygeodesy.unstr}.
402 '''
403 n = _DOT_(self, which.__name__ if callable(which) else _NN_)
404 return unstr(n, *args, **kwds)
406 def _xnamed(self, inst, name=NN, force=False):
407 '''(INTERNAL) Set the instance' C{.name = self.name}.
409 @arg inst: The instance (C{_Named}).
410 @kwarg name: Optional name, overriding C{self.name} (C{str}).
411 @kwarg force: Force name change (C{bool}).
413 @return: The B{C{inst}}, named if not named before.
414 '''
415 return _xnamed(inst, name or self.name, force=force)
417 def _xrenamed(self, inst):
418 '''(INTERNAL) Rename the instance' C{.name = self.name}.
420 @arg inst: The instance (C{_Named}).
422 @return: The B{C{inst}}, named if not named before.
424 @raise TypeError: Not C{isinstance(B{inst}, _Named)}.
425 '''
426 if not isinstance(inst, _Named):
427 raise _IsnotError(_valid_, inst=inst)
429 inst.rename(self.name)
430 return inst
432_Named_Property_ROs = _allPropertiesOf_n(5, _Named, Property_RO) # PYCHOK once
435class _NamedBase(_Named):
436 '''(INTERNAL) Base class with name.
437 '''
438 def __repr__(self):
439 '''Default C{repr(self)}.
440 '''
441 return self.toRepr()
443 def __str__(self):
444 '''Default C{str(self)}.
445 '''
446 return self.toStr()
448# def notImplemented(self, attr):
449# '''Raise error for a missing method, function or attribute.
450#
451# @arg attr: Attribute name (C{str}).
452#
453# @raise NotImplementedError: No such attribute.
454# '''
455# c = self.__class__.__name__
456# return NotImplementedError(_DOT_(c, attr))
458 def others(self, *other, **name_other_up):
459 '''Refined class comparison, invoked as C{.others(other)},
460 C{.others(name=other)} or C{.others(other, name='other')}.
462 @arg other: The other instance (any C{type}).
463 @kwarg name_other_up: Overriding C{name=other} and C{up=1}
464 keyword arguments.
466 @return: The B{C{other}} iff compatible with this instance's
467 C{class} or C{type}.
469 @raise TypeError: Mismatch of the B{C{other}} and this
470 instance's C{class} or C{type}.
471 '''
472 if other: # most common, just one arg B{C{other}}
473 other0 = other[0]
474 if isinstance(other0, self.__class__) or \
475 isinstance(self, other0.__class__):
476 return other0
478 other, name, up = _xother3(self, other, **name_other_up)
479 if isinstance(self, other.__class__) or \
480 isinstance(other, self.__class__):
481 return _xnamed(other, name)
483 raise _xotherError(self, other, name=name, up=up + 1)
485 def toRepr(self, **kwds): # PYCHOK expected
486 '''(INTERNAL) I{Could be overloaded}.
488 @kwarg kwds: Optional, C{toStr} keyword arguments.
490 @return: C{toStr}() with keyword arguments (as C{str}).
491 '''
492 t = lrstrip(self.toStr(**kwds))
493# if self.name:
494# t = NN(Fmt.EQUAL(name=repr(self.name)), sep, t)
495 return Fmt.PAREN(self.classname, t) # XXX (self.named, t)
497# def toRepr(self, **kwds)
498# if kwds:
499# s = NN.join(reprs((self,), **kwds))
500# else: # super().__repr__ only for Python 3+
501# s = super(self.__class__, self).__repr__()
502# return Fmt.PAREN(self.named, s) # clips(s)
504 def toStr(self, **kwds): # PYCHOK no cover
505 '''I{Must be overloaded}.'''
506 notOverloaded(self, **kwds)
508# def toStr(self, **kwds):
509# if kwds:
510# s = NN.join(strs((self,), **kwds))
511# else: # super().__str__ only for Python 3+
512# s = super(self.__class__, self).__str__()
513# return s
515 def _update(self, updated, *attrs, **setters):
516 '''(INTERNAL) Zap cached instance attributes and overwrite C{__dict__} or L{Property_RO} values.
517 '''
518 u = _update_all(self, *attrs) if updated else 0
519 if setters:
520 d = self.__dict__
521 # double-check that setters are Property_RO's
522 for n, v in setters.items():
523 if n in d or _hasProperty(self, n, Property_RO):
524 d[n] = v
525 else:
526 raise _AssertionError(n, v, txt=repr(self))
527 u += len(setters)
528 return u
531class _NamedDict(_Dict, _Named):
532 '''(INTERNAL) Named C{dict} with key I{and} attribute
533 access to the items.
534 '''
535 def __init__(self, *args, **kwds):
536 if args: # args override kwds
537 if len(args) != 1:
538 t = unstr(self.classname, *args, **kwds) # PYCHOK no cover
539 raise _ValueError(args=len(args), txt=t)
540 kwds = _xkwds(dict(args[0]), **kwds)
541 if _name_ in kwds:
542 _Named.name.fset(self, kwds.pop(_name_)) # see _Named.name
543 _Dict.__init__(self, kwds)
545 def __delattr__(self, name):
546 '''Delete an attribute or item by B{C{name}}.
547 '''
548 if name in _Dict.keys(self):
549 _Dict.pop(name)
550 elif name in (_name_, _name):
551 # _Dict.__setattr__(self, name, NN)
552 _Named.rename(self, NN)
553 else:
554 _Dict.__delattr__(self, name)
556 def __getattr__(self, name):
557 '''Get an attribute or item by B{C{name}}.
558 '''
559 try:
560 return self[name]
561 except KeyError:
562 if name == _name_:
563 return _Named.name.fget(self)
564 raise _AttributeError(item=self._DOT_(name), txt=_doesn_t_exist_)
566 def __getitem__(self, key):
567 '''Get the value of an item by B{C{key}}.
568 '''
569 if key == _name_:
570 raise KeyError(Fmt.SQUARE(self.classname, key))
571 return _Dict.__getitem__(self, key)
573 def __setattr__(self, name, value):
574 '''Set attribute or item B{C{name}} to B{C{value}}.
575 '''
576 if name in _Dict.keys(self):
577 _Dict.__setitem__(self, name, value) # self[name] = value
578 else:
579 _Dict.__setattr__(self, name, value)
581 def __setitem__(self, key, value):
582 '''Set item B{C{key}} to B{C{value}}.
583 '''
584 if key == _name_:
585 raise KeyError(_EQUAL_(Fmt.SQUARE(self.classname, key), repr(value)))
586 _Dict.__setitem__(self, key, value)
588 def toRepr(self, **prec_fmt): # PYCHOK signature
589 '''Like C{repr(dict)} but with C{name} prefix and with
590 C{floats} formatted by function L{pygeodesy.fstr}.
591 '''
592 return Fmt.PAREN(self.name, self._toT(_EQUAL_, **prec_fmt))
594 def toStr(self, **prec_fmt): # PYCHOK signature
595 '''Like C{str(dict)} but with C{floats} formatted by
596 function L{pygeodesy.fstr}.
597 '''
598 return Fmt.CURLY(self._toT(_COLONSPACE_, **prec_fmt))
601class _NamedEnum(_NamedDict):
602 '''(INTERNAL) Enum-like C{_NamedDict} with attribute access
603 restricted to valid keys.
604 '''
605 _item_Classes = ()
607 def __init__(self, Class, *Classes, **name):
608 '''New C{_NamedEnum}.
610 @arg Class: Initial class or type acceptable as items
611 values (C{type}).
612 @arg Classes: Additional, acceptable classes or C{type}s.
613 '''
614 self._item_Classes = (Class,) + Classes
615 n = _xkwds_get(name, name=NN) or NN(Class.__name__, _s_)
616 if n and _xvalid(n, _OK=True):
617 _Named.name.fset(self, n) # see _Named.name
619 def __getattr__(self, name):
620 '''Get the value of an attribute or item by B{C{name}}.
621 '''
622 try:
623 return self[name]
624 except KeyError:
625 if name == _name_:
626 return _NamedDict.name.fget(self)
627 raise _AttributeError(item=self._DOT_(name), txt=_doesn_t_exist_)
629 def __repr__(self):
630 '''Default C{repr(self)}.
631 '''
632 return self.toRepr()
634 def __str__(self):
635 '''Default C{str(self)}.
636 '''
637 return self.toStr()
639 def _assert(self, **kwds):
640 '''(INTERNAL) Check attribute name against given, registered name.
641 '''
642 pypy = _isPyPy()
643 for n, v in kwds.items():
644 if isinstance(v, _LazyNamedEnumItem): # property
645 assert (n == v.name) if pypy else (n is v.name)
646 # assert not hasattr(self.__class__, n)
647 setattr(self.__class__, n, v)
648 elif isinstance(v, self._item_Classes): # PYCHOK no cover
649 assert self[n] is v and getattr(self, n) \
650 and self.find(v) == n
651 else:
652 raise _TypeError(v, name=n)
654 def find(self, item, dflt=None):
655 '''Find a registered item.
657 @arg item: The item to look for (any C{type}).
658 @kwarg dflt: Value to return if not found (any C{type}).
660 @return: The B{C{item}}'s name if found (C{str}), or C{{dflt}} if
661 there is no such I{registered} B{C{item}}.
662 '''
663 for k, v in self.items(): # or _Dict.items(self)
664 if v is item:
665 return k
666 return dflt
668 def get(self, name, dflt=None):
669 '''Get the value of a I{registered} item.
671 @arg name: The name of the item (C{str}).
672 @kwarg dflt: Value to return (any C{type}).
674 @return: The item with B{C{name}} if found, or B{C{dflt}} if
675 there is no item I{registered} with that B{C{name}}.
676 '''
677 # getattr needed to instantiate L{_LazyNamedEnumItem}
678 return getattr(self, name, dflt)
680 def items(self, all=False, asorted=False):
681 '''Yield all or only the I{registered} items.
683 @kwarg all: Use C{True} to yield {all} items or C{False}
684 for only the currently I{registered} ones.
685 @kwarg asorted: If C{True}, yield the items sorted in
686 I{alphabetical, case-insensitive} order.
687 '''
688 if all: # instantiate any remaining L{_LazyNamedEnumItem} ...
689 # ... and remove the L{_LazyNamedEnumItem} from the class
690 for n in tuple(n for n, p in self.__class__.__dict__.items()
691 if isinstance(p, _LazyNamedEnumItem)):
692 _ = getattr(self, n)
693 return itemsorted(self) if asorted else _Dict.items(self)
695 def keys(self, **all_asorted):
696 '''Yield the keys (C{str}) of all or only the I{registered} items,
697 optionally sorted I{alphabetically} and I{case-insensitively}.
699 @kwarg all_asorted: See method C{items}..
700 '''
701 for k, _ in self.items(**all_asorted):
702 yield k
704 def popitem(self):
705 '''Remove I{an, any} curretly I{registed} item.
707 @return: The removed item.
708 '''
709 return self._zapitem(*_Dict.pop(self))
711 def register(self, item):
712 '''Registed a new item.
714 @arg item: The item (any C{type}).
716 @return: The item name (C{str}).
718 @raise NameError: An B{C{item}} already registered with
719 that name or the B{C{item}} has no, an
720 empty or an invalid name.
722 @raise TypeError: The B{C{item}} type invalid.
723 '''
724 try:
725 n = item.name
726 if not (n and isstr(n) and isidentifier(n)):
727 raise ValueError
728 except (AttributeError, ValueError, TypeError) as x:
729 raise _NameError(_DOT_(_item_, _name_), item, cause=x)
730 if n in self:
731 raise _NameError(self._DOT_(n), item, txt=_exists_)
732 if not (self._item_Classes and isinstance(item, self._item_Classes)):
733 raise _TypesError(self._DOT_(n), item, *self._item_Classes)
734 self[n] = item
736 def unregister(self, name_or_item):
737 '''Remove a I{registered} item.
739 @arg name_or_item: Name (C{str}) or the item (any C{type}).
741 @return: The unregistered item.
743 @raise NameError: No item with that B{C{name}}.
745 @raise ValueError: No such item.
746 '''
747 if isstr(name_or_item):
748 name = name_or_item
749 else:
750 name = self.find(name_or_item)
751 try:
752 item = _Dict.pop(self, name)
753 except KeyError:
754 raise _NameError(item=self._DOT_(name), txt=_doesn_t_exist_)
755 return self._zapitem(name, item)
757 pop = unregister
759 def toRepr(self, prec=6, fmt=Fmt.F, sep=_COMMANL_, **all_asorted): # PYCHOK _NamedDict
760 '''Like C{repr(dict)} but C{name}s optionally sorted and
761 C{floats} formatted by function L{pygeodesy.fstr}.
762 '''
763 t = ((self._DOT_(n), v) for n, v in self.items(**all_asorted))
764 return sep.join(pairs(t, prec=prec, fmt=fmt, sep=_COLONSPACE_))
766 def toStr(self, *unused, **all_asorted): # PYCHOK _NamedDict
767 '''Return a string with all C{name}s, optionally sorted.
768 '''
769 return self._DOT_(_COMMASPACEDOT_.join(self.keys(**all_asorted)))
771 def values(self, **all_asorted):
772 '''Yield the value (C{type}) of all or only the I{registered} items,
773 optionally sorted I{alphabetically} and I{case-insensitively}.
775 @kwarg all_asorted: See method C{items}.
776 '''
777 for _, v in self.items(**all_asorted):
778 yield v
780 def _zapitem(self, name, item):
781 # remove _LazyNamedEnumItem property value if still present
782 if self.__dict__.get(name, None) is item:
783 self.__dict__.pop(name) # [name] = None
784 item._enum = None
785 return item
788class _LazyNamedEnumItem(property_RO): # XXX or descriptor?
789 '''(INTERNAL) Lazily instantiated L{_NamedEnumItem}.
790 '''
791 pass
794def _lazyNamedEnumItem(name, *args, **kwds):
795 '''(INTERNAL) L{_LazyNamedEnumItem} property-like factory.
797 @see: Luciano Ramalho, "Fluent Python", O'Reilly, Example
798 19-24, 2016 p. 636 or Example 22-28, 2022 p. 869+
799 '''
800 def _fget(inst):
801 # assert isinstance(inst, _NamedEnum)
802 try: # get the item from the instance' __dict__
803 # item = inst.__dict__[name] # ... or _Dict
804 item = inst[name]
805 except KeyError:
806 # instantiate an _NamedEnumItem, it self-registers
807 item = inst._Lazy(*args, **_xkwds(kwds, name=name))
808 # assert inst[name] is item # MUST be registered
809 # store the item in the instance' __dict__ ...
810 # inst.__dict__[name] = item # ... or update the
811 inst.update({name: item}) # ... _Dict for Triaxials
812 # remove the property from the registry class, such that
813 # (a) the property no longer overrides the instance' item
814 # in inst.__dict__ and (b) _NamedEnum.items(all=True) only
815 # sees any un-instantiated ones yet to be instantiated
816 p = getattr(inst.__class__, name, None)
817 if isinstance(p, _LazyNamedEnumItem):
818 delattr(inst.__class__, name)
819 # assert isinstance(item, _NamedEnumItem)
820 return item
822 p = _LazyNamedEnumItem(_fget)
823 p.name = name
824 return p
827class _NamedEnumItem(_NamedBase):
828 '''(INTERNAL) Base class for items in a C{_NamedEnum} registery.
829 '''
830 _enum = None
832# def __ne__(self, other): # XXX fails for Lcc.conic = conic!
833# '''Compare this and an other item.
834#
835# @return: C{True} if different, C{False} otherwise.
836# '''
837# return not self.__eq__(other)
839 @property_doc_(''' the I{registered} name (C{str}).''')
840 def name(self):
841 '''Get the I{registered} name (C{str}).
842 '''
843 return self._name
845 @name.setter # PYCHOK setter!
846 def name(self, name):
847 '''Set the name, unless already registered (C{str}).
848 '''
849 if self._enum:
850 raise _NameError(str(name), self, txt=_registered_) # XXX _TypeError
851 self._name = str(name)
853 def _register(self, enum, name):
854 '''(INTERNAL) Add this item as B{C{enum.name}}.
856 @note: Don't register if name is empty or doesn't
857 start with a letter.
858 '''
859 if name and _xvalid(name, _OK=True):
860 self.name = name
861 if name[:1].isalpha(): # '_...' not registered
862 enum.register(self)
863 self._enum = enum
865 def unregister(self):
866 '''Remove this instance from its C{_NamedEnum} registry.
868 @raise AssertionError: Mismatch of this and registered item.
870 @raise NameError: This item is unregistered.
871 '''
872 enum = self._enum
873 if enum and self.name and self.name in enum:
874 item = enum.unregister(self.name)
875 if item is not self:
876 t = _SPACE_(repr(item), _vs_, repr(self)) # PYCHOK no cover
877 raise _AssertionError(t)
880class _NamedTuple(tuple, _Named):
881 '''(INTERNAL) Base for named C{tuple}s with both index I{and}
882 attribute name access to the items.
884 @note: This class is similar to Python's C{namedtuple},
885 but statically defined, lighter and limited.
886 '''
887 _Names_ = () # item names, non-identifier, no leading underscore
888 '''Tuple specifying the C{name} of each C{Named-Tuple} item.
890 @note: Specify at least 2 item names.
891 '''
892 _Units_ = () # .units classes
893 '''Tuple defining the C{units} of the value of each C{Named-Tuple} item.
895 @note: The C{len(_Units_)} must match C{len(_Names_)}.
896 '''
897 _validated = False # set to True I{per sub-class!}
899 def __new__(cls, arg, *args, **iteration_name):
900 '''New L{_NamedTuple} initialized with B{C{positional}} arguments.
902 @arg arg: Tuple items (C{tuple}, C{list}, ...) or first tuple
903 item of several more in other positional arguments.
904 @arg args: Tuple items (C{any}), all positional arguments.
905 @kwarg iteration_name: Only keyword arguments C{B{iteration}=None}
906 and C{B{name}=NN} are used, any other are
907 I{silently} ignored.
909 @raise LenError: Unequal number of positional arguments and
910 number of item C{_Names_} or C{_Units_}.
912 @raise TypeError: The C{_Names_} or C{_Units_} attribute is
913 not a C{tuple} of at least 2 items.
915 @raise ValueError: Item name is not a C{str} or valid C{identifier}
916 or starts with C{underscore}.
917 '''
918 n, args = len2(((arg,) + args) if args else arg)
919 self = tuple.__new__(cls, args)
920 if not self._validated:
921 self._validate()
923 N = len(self._Names_)
924 if n != N:
925 raise LenError(self.__class__, args=n, _Names_=N)
927 if iteration_name:
928 self._kwdself(**iteration_name)
929 return self
931 def __delattr__(self, name):
932 '''Delete an attribute by B{C{name}}.
934 @note: Items can not be deleted.
935 '''
936 if name in self._Names_:
937 raise _TypeError(_del_, _DOT_(self.classname, name), txt=_immutable_)
938 elif name in (_name_, _name):
939 _Named.__setattr__(self, name, NN) # XXX _Named.name.fset(self, NN)
940 else:
941 tuple.__delattr__(self, name)
943 def __getattr__(self, name):
944 '''Get the value of an attribute or item by B{C{name}}.
945 '''
946 try:
947 return tuple.__getitem__(self, self._Names_.index(name))
948 except IndexError:
949 raise _IndexError(_DOT_(self.classname, Fmt.ANGLE(_name_)), name)
950 except ValueError: # e.g. _iteration
951 return tuple.__getattribute__(self, name)
953# def __getitem__(self, index): # index, slice, etc.
954# '''Get the item(s) at an B{C{index}} or slice.
955# '''
956# return tuple.__getitem__(self, index)
958 def __repr__(self):
959 '''Default C{repr(self)}.
960 '''
961 return self.toRepr()
963 def __setattr__(self, name, value):
964 '''Set attribute or item B{C{name}} to B{C{value}}.
965 '''
966 if name in self._Names_:
967 raise _TypeError(_DOT_(self.classname, name), value, txt=_immutable_)
968 elif name in (_name_, _name):
969 _Named.__setattr__(self, name, value) # XXX _Named.name.fset(self, value)
970 else: # e.g. _iteration
971 tuple.__setattr__(self, name, value)
973 def __str__(self):
974 '''Default C{repr(self)}.
975 '''
976 return self.toStr()
978 def dup(self, name=NN, **items):
979 '''Duplicate this tuple replacing one or more items.
981 @kwarg name: Optional new name (C{str}).
982 @kwarg items: Items to be replaced (C{name=value} pairs), if any.
984 @return: A copy of this tuple with B{C{items}}.
986 @raise NameError: Some B{C{items}} invalid.
987 '''
988 tl = list(self)
989 if items:
990 _ix = self._Names_.index
991 try:
992 for n, v in items.items():
993 tl[_ix(n)] = v
994 except ValueError: # bad item name
995 raise _NameError(_DOT_(self.classname, n), v, this=self)
996 return self.classof(*tl, name=name or self.name)
998 def items(self):
999 '''Yield the items, each as a C{(name, value)} pair (C{2-tuple}).
1001 @see: Method C{.units}.
1002 '''
1003 for n, v in _zip(self._Names_, self): # strict=True
1004 yield n, v
1006 iteritems = items
1008 def _kwdself(self, iteration=None, name=NN, **unused):
1009 '''(INTERNAL) Set C{__new__} keyword arguments.
1010 '''
1011 if iteration is not None:
1012 self._iteration = iteration
1013 if name:
1014 self.name = name
1016 def toRepr(self, prec=6, sep=_COMMASPACE_, fmt=Fmt.F, **unused): # PYCHOK signature
1017 '''Return this C{Named-Tuple} items as C{name=value} string(s).
1019 @kwarg prec: The C{float} precision, number of decimal digits (0..9).
1020 Trailing zero decimals are stripped for B{C{prec}} values
1021 of 1 and above, but kept for negative B{C{prec}} values.
1022 @kwarg sep: Separator to join (C{str}).
1023 @kwarg fmt: Optional, C{float} format (C{str}).
1025 @return: Tuple items (C{str}).
1026 '''
1027 t = pairs(self.items(), prec=prec, fmt=fmt)
1028# if self.name:
1029# t = (Fmt.EQUAL(name=repr(self.name)),) + t
1030 return Fmt.PAREN(self.named, sep.join(t)) # XXX (self.classname, sep.join(t))
1032 def toStr(self, prec=6, sep=_COMMASPACE_, fmt=Fmt.F, **unused): # PYCHOK signature
1033 '''Return this C{Named-Tuple} items as string(s).
1035 @kwarg prec: The C{float} precision, number of decimal digits (0..9).
1036 Trailing zero decimals are stripped for B{C{prec}} values
1037 of 1 and above, but kept for negative B{C{prec}} values.
1038 @kwarg sep: Separator to join (C{str}).
1039 @kwarg fmt: Optional C{float} format (C{str}).
1041 @return: Tuple items (C{str}).
1042 '''
1043 return Fmt.PAREN(sep.join(reprs(self, prec=prec, fmt=fmt)))
1045 def toUnits(self, Error=UnitError): # overloaded in .frechet, .hausdorff
1046 '''Return a copy of this C{Named-Tuple} with each item value wrapped
1047 as an instance of its L{units} class.
1049 @kwarg Error: Error to raise for L{units} issues (C{UnitError}).
1051 @return: A duplicate of this C{Named-Tuple} (C{C{Named-Tuple}}).
1053 @raise Error: Invalid C{Named-Tuple} item or L{units} class.
1054 '''
1055 t = (v for _, v in self.units(Error=Error))
1056 return self.classof(*tuple(t))
1058 def units(self, Error=UnitError):
1059 '''Yield the items, each as a C{(name, value}) pair (C{2-tuple}) with
1060 the value wrapped as an instance of its L{units} class.
1062 @kwarg Error: Error to raise for L{units} issues (C{UnitError}).
1064 @raise Error: Invalid C{Named-Tuple} item or L{units} class.
1066 @see: Method C{.items}.
1067 '''
1068 for n, v, U in _zip(self._Names_, self, self._Units_): # strict=True
1069 if not (v is None or U is None
1070 or (isclass(U) and
1071 isinstance(v, U) and
1072 hasattr(v, _name_) and
1073 v.name == n)): # PYCHOK indent
1074 v = U(v, name=n, Error=Error)
1075 yield n, v
1077 iterunits = units
1079 def _validate(self, _OK=False): # see .EcefMatrix
1080 '''(INTERNAL) One-time check of C{_Names_} and C{_Units_}
1081 for each C{_NamedUnit} I{sub-class separately}.
1082 '''
1083 ns = self._Names_
1084 if not (isinstance(ns, tuple) and len(ns) > 1): # XXX > 0
1085 raise _TypeError(_DOT_(self.classname, _Names_), ns)
1086 for i, n in enumerate(ns):
1087 if not _xvalid(n, _OK=_OK):
1088 t = Fmt.SQUARE(_Names_=i) # PYCHOK no cover
1089 raise _ValueError(_DOT_(self.classname, t), n)
1091 us = self._Units_
1092 if not isinstance(us, tuple):
1093 raise _TypeError(_DOT_(self.classname, _Units_), us)
1094 if len(us) != len(ns):
1095 raise LenError(self.__class__, _Units_=len(us), _Names_=len(ns))
1096 for i, u in enumerate(us):
1097 if not (u is None or callable(u)):
1098 t = Fmt.SQUARE(_Units_=i) # PYCHOK no cover
1099 raise _TypeError(_DOT_(self.classname, t), u)
1101 self.__class__._validated = True
1103 def _xtend(self, xTuple, *items):
1104 '''(INTERNAL) Extend this C{Named-Tuple} with C{items} to an other B{C{xTuple}}.
1105 '''
1106 if (issubclassof(xTuple, _NamedTuple) and
1107 (len(self._Names_) + len(items)) == len(xTuple._Names_) and
1108 self._Names_ == xTuple._Names_[:len(self)]):
1109 return self._xnamed(xTuple(self + items)) # *(self + items)
1110 c = NN(self.classname, repr(self._Names_)) # PYCHOK no cover
1111 x = NN(xTuple.__name__, repr(xTuple._Names_)) # PYCHOK no cover
1112 raise TypeError(_SPACE_(c, _vs_, x))
1115def callername(up=1, dflt=NN, source=False, underOK=False):
1116 '''Get the name of the invoking callable.
1118 @kwarg up: Number of call stack frames up (C{int}).
1119 @kwarg dflt: Default return value (C{any}).
1120 @kwarg source: Include source file name and line number (C{bool}).
1121 @kwarg underOK: If C{True}, private, internal callables are OK,
1122 otherwise private callables are skipped (C{bool}).
1124 @return: The callable name (C{str}) or B{C{dflt}} if none found.
1125 '''
1126 try: # see .lazily._caller3
1127 for u in range(up, up + 32):
1128 n, f, s = _caller3(u)
1129 if n and (underOK or n.startswith(_DUNDER_) or
1130 not n.startswith(_UNDER_)):
1131 if source:
1132 n = NN(n, _AT_, f, _COLON_, str(s))
1133 return n
1134 except (AttributeError, ValueError):
1135 pass
1136 return dflt
1139def _callername2(args, callername=NN, source=False, underOK=False, up=2, **kwds):
1140 '''(INTERNAL) Extract C{callername}, C{source}, C{underOK} and C{up} from C{kwds}.
1141 '''
1142 n = callername or _MODS.named.callername(up=up + 1, source=source,
1143 underOK=underOK or bool(args or kwds))
1144 return n, kwds
1147def _callname(name, class_name, self_name, up=1):
1148 '''(INTERNAL) Assemble the name for an invokation.
1149 '''
1150 n, c = class_name, callername(up=up + 1)
1151 if c:
1152 n = _DOT_(n, Fmt.PAREN(c, name))
1153 if self_name:
1154 n = _SPACE_(n, repr(self_name))
1155 return n
1158def classname(inst, prefixed=None):
1159 '''Return the instance' class name optionally prefixed with the
1160 module name.
1162 @arg inst: The object (any C{type}).
1163 @kwarg prefixed: Include the module name (C{bool}), see
1164 function C{classnaming}.
1166 @return: The B{C{inst}}'s C{[module.]class} name (C{str}).
1167 '''
1168 if prefixed is None:
1169 prefixed = getattr(inst, classnaming.__name__, prefixed)
1170 return modulename(inst.__class__, prefixed=prefixed)
1173def classnaming(prefixed=None):
1174 '''Get/set the default class naming for C{[module.]class} names.
1176 @kwarg prefixed: Include the module name (C{bool}).
1178 @return: Previous class naming setting (C{bool}).
1179 '''
1180 t = _Named._classnaming
1181 if prefixed in (True, False):
1182 _Named._classnaming = prefixed
1183 return t
1186def modulename(clas, prefixed=None): # in .basics._xversion
1187 '''Return the class name optionally prefixed with the
1188 module name.
1190 @arg clas: The class (any C{class}).
1191 @kwarg prefixed: Include the module name (C{bool}), see
1192 function C{classnaming}.
1194 @return: The B{C{class}}'s C{[module.]class} name (C{str}).
1195 '''
1196 try:
1197 n = clas.__name__
1198 except AttributeError:
1199 n = '__name__' # _DUNDER_(NN, _name_, NN)
1200 if prefixed or (classnaming() if prefixed is None else False):
1201 try:
1202 m = clas.__module__.rsplit(_DOT_, 1)
1203 n = _DOT_.join(m[1:] + [n])
1204 except AttributeError:
1205 pass
1206 return n
1209def nameof(inst):
1210 '''Get the name of an instance.
1212 @arg inst: The object (any C{type}).
1214 @return: The instance' name (C{str}) or C{""}.
1215 '''
1216 n = _xattr(inst, name=NN)
1217 if not n: # and isinstance(inst, property):
1218 try:
1219 n = inst.fget.__name__
1220 except AttributeError:
1221 n = NN
1222 return n
1225def _notDecaps(where):
1226 '''De-Capitalize C{where.__name__}.
1227 '''
1228 n = where.__name__
1229 c = n[3].lower() # len(_not_)
1230 return NN(n[:3], _SPACE_, c, n[4:])
1233def _notError(inst, name, args, kwds): # PYCHOK no cover
1234 '''(INTERNAL) Format an error message.
1235 '''
1236 n = _DOT_(classname(inst, prefixed=True), _dunder_nameof(name, name))
1237 m = _COMMASPACE_.join(modulename(c, prefixed=True) for c in inst.__class__.__mro__[1:-1])
1238 return _COMMASPACE_(unstr(n, *args, **kwds), Fmt.PAREN(_MRO_, m))
1241def _NotImplemented(inst, *other, **kwds):
1242 '''(INTERNAL) Raise a C{__special__} error or return C{NotImplemented},
1243 but only if env variable C{PYGEODESY_NOTIMPLEMENTED=std}.
1244 '''
1245 if _std_NotImplemented:
1246 return NotImplemented
1247 n, kwds = _callername2(other, **kwds) # source=True
1248 t = unstr(_DOT_(classname(inst), n), *other, **kwds)
1249 raise _NotImplementedError(t, txt=repr(inst))
1252def notImplemented(inst, *args, **kwds): # PYCHOK no cover
1253 '''Raise a C{NotImplementedError} for a missing instance method or
1254 property or for a missing caller feature.
1256 @arg inst: Instance (C{any}) or C{None} for caller.
1257 @arg args: Method or property positional arguments (any C{type}s).
1258 @arg kwds: Method or property keyword arguments (any C{type}s),
1259 except C{B{callername}=NN}, C{B{underOK}=False} and
1260 C{B{up}=2}.
1261 '''
1262 n, kwds = _callername2(args, **kwds)
1263 t = _notError(inst, n, args, kwds) if inst else unstr(n, *args, **kwds)
1264 raise _NotImplementedError(t, txt=_notDecaps(notImplemented))
1267def notOverloaded(inst, *args, **kwds): # PYCHOK no cover
1268 '''Raise an C{AssertionError} for a method or property not overloaded.
1270 @arg inst: Instance (C{any}).
1271 @arg args: Method or property positional arguments (any C{type}s).
1272 @arg kwds: Method or property keyword arguments (any C{type}s),
1273 except C{B{callername}=NN}, C{B{underOK}=False} and
1274 C{B{up}=2}.
1275 '''
1276 n, kwds = _callername2(args, **kwds)
1277 t = _notError(inst, n, args, kwds)
1278 raise _AssertionError(t, txt=_notDecaps(notOverloaded))
1281def _Pass(arg, **unused): # PYCHOK no cover
1282 '''(INTERNAL) I{Pass-thru} class for C{_NamedTuple._Units_}.
1283 '''
1284 return arg
1287__all__ += _ALL_DOCS(_Named,
1288 _NamedBase, # _NamedDict,
1289 _NamedEnum, _NamedEnumItem,
1290 _NamedTuple)
1292# **) MIT License
1293#
1294# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.
1295#
1296# Permission is hereby granted, free of charge, to any person obtaining a
1297# copy of this software and associated documentation files (the "Software"),
1298# to deal in the Software without restriction, including without limitation
1299# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1300# and/or sell copies of the Software, and to permit persons to whom the
1301# Software is furnished to do so, subject to the following conditions:
1302#
1303# The above copyright notice and this permission notice shall be included
1304# in all copies or substantial portions of the Software.
1305#
1306# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1307# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1308# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1309# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1310# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1311# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1312# OTHER DEALINGS IN THE SOFTWARE.
1314# % env PYGEODESY_FOR_DOCS=1 python -m pygeodesy.named
1315# all 71 locals OK