Coverage for pygeodesy/named.py: 96%
523 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-09 12:50 -0400
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-09 12:50 -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 isidentifier, iskeyword, isstr, itemsorted, len2, \
17 _xcopy, _xdup, _xinstanceof, _xsubclassof, _zip
18from pygeodesy.errors import _AssertionError, _AttributeError, _incompatible, \
19 _IndexError, _KeyError, LenError, _NameError, \
20 _NotImplementedError, _TypeError, _TypesError, \
21 _UnexpectedError, UnitError, _ValueError, \
22 _xattr, _xkwds, _xkwds_item2, _xkwds_pop2
23from pygeodesy.internals import _caller3, _dunder_nameof, _isPyPy, _sizeof, _under
24from pygeodesy.interns import MISSING, NN, _AT_, _COLON_, _COLONSPACE_, _COMMA_, \
25 _COMMASPACE_, _doesn_t_exist_, _DOT_, _DUNDER_, \
26 _dunder_name_, _EQUAL_, _exists_, _immutable_, _name_, \
27 _NL_, _NN_, _no_, _other_, _s_, _SPACE_, _std_, \
28 _UNDER_, _vs_
29from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS, _getenv
30from pygeodesy.props import _allPropertiesOf_n, deprecated_method, _hasProperty, \
31 _update_all, property_doc_, Property_RO, property_RO, \
32 _update_attrs
33from pygeodesy.streprs import attrs, Fmt, lrstrip, pairs, reprs, unstr
34# from pygeodesy.units import _toUnit # _MODS
36__all__ = _ALL_LAZY.named
37__version__ = '24.09.02'
39_COMMANL_ = _COMMA_ + _NL_
40_COMMASPACEDOT_ = _COMMASPACE_ + _DOT_
41_del_ = 'del'
42_item_ = 'item'
43_MRO_ = 'MRO'
44# __DUNDER gets mangled in class
45_name = _under(_name_)
46_Names_ = '_Names_'
47_registered_ = 'registered' # PYCHOK used!
48_std_NotImplemented = _getenv('PYGEODESY_NOTIMPLEMENTED', NN).lower() == _std_
49_such_ = 'such'
50_Units_ = '_Units_'
51_UP = 2
54class ADict(dict):
55 '''A C{dict} with both key I{and} attribute access to
56 the C{dict} items.
57 '''
58 _iteration = None # Iteration number (C{int}) or C{None}
60 def __getattr__(self, name):
61 '''Get the value of an item by B{C{name}}.
62 '''
63 try:
64 return self[name]
65 except KeyError:
66 if name == _name_:
67 return NN
68 raise self._AttributeError(name)
70 def __repr__(self):
71 '''Default C{repr(self)}.
72 '''
73 return self.toRepr()
75 def __setattr__(self, name, value):
76 '''Set the value of a I{known} item by B{C{name}}.
77 '''
78 try:
79 if self[name] != value:
80 self[name] = value
81 except KeyError:
82 dict.__setattr__(self, name, value)
84 def __str__(self):
85 '''Default C{str(self)}.
86 '''
87 return self.toStr()
89 def _AttributeError(self, name):
90 '''(INTERNAL) Create an C{AttributeError}.
91 '''
92 if _DOT_ not in name: # NOT classname(self)!
93 name = _DOT_(self.__class__.__name__, name)
94 return _AttributeError(item=name, txt=_doesn_t_exist_)
96 @property_RO
97 def iteration(self): # see .named._NamedBase
98 '''Get the iteration number (C{int}) or
99 C{None} if not available/applicable.
100 '''
101 return self._iteration
103 def set_(self, iteration=None, **items): # PYCHOK signature
104 '''Add one or several new items or replace existing ones.
106 @kwarg iteration: Optional C{iteration} (C{int}).
107 @kwarg items: One or more C{name=value} pairs.
108 '''
109 if iteration is not None:
110 self._iteration = iteration
111 if items:
112 dict.update(self, items)
113 return self # in RhumbLineBase.Intersecant2, _PseudoRhumbLine.Position
115 def toRepr(self, **prec_fmt):
116 '''Like C{repr(dict)} but with C{name} prefix and with
117 C{floats} formatted by function L{pygeodesy.fstr}.
118 '''
119 n = _xattr(self, name=NN) or self.__class__.__name__
120 return Fmt.PAREN(n, self._toT(_EQUAL_, **prec_fmt))
122 def toStr(self, **prec_fmt):
123 '''Like C{str(dict)} but with C{floats} formatted by
124 function L{pygeodesy.fstr}.
125 '''
126 return Fmt.CURLY(self._toT(_COLONSPACE_, **prec_fmt))
128 def _toT(self, sep, **kwds):
129 '''(INTERNAL) Helper for C{.toRepr} and C{.toStr}.
130 '''
131 kwds = _xkwds(kwds, prec=6, fmt=Fmt.F, sep=sep)
132 return _COMMASPACE_.join(pairs(itemsorted(self), **kwds))
135class _Named(object):
136 '''(INTERNAL) Root class for named objects.
137 '''
138 _iteration = None # iteration number (C{int}) or C{None}
139 _name = NN # name (C{str})
140 _classnaming = False # prefixed (C{bool})
141# _updates = 0 # OBSOLETE Property/property updates
143 def __imatmul__(self, other): # PYCHOK no cover
144 '''Not implemented.'''
145 return _NotImplemented(self, other) # PYCHOK Python 3.5+
147 def __matmul__(self, other): # PYCHOK no cover
148 '''Not implemented.'''
149 return _NotImplemented(self, other) # PYCHOK Python 3.5+
151 def __repr__(self):
152 '''Default C{repr(self)}.
153 '''
154 return Fmt.repr_at(self)
156 def __rmatmul__(self, other): # PYCHOK no cover
157 '''Not implemented.'''
158 return _NotImplemented(self, other) # PYCHOK Python 3.5+
160 def __str__(self):
161 '''Default C{str(self)}.
162 '''
163 return self.named2
165 def attrs(self, *names, **sep_Nones_pairs_kwds):
166 '''Join named attributes as I{name=value} strings, with C{float}s formatted by
167 function L{pygeodesy.fstr}.
169 @arg names: The attribute names, all positional (C{str}).
170 @kwarg sep_Nones_pairs_kwds: Keyword arguments for function L{pygeodesy.pairs},
171 except C{B{sep}=", "} and C{B{Nones}=True} to in-/exclude missing
172 or C{None}-valued attributes.
174 @return: All C{name=value} pairs, joined by B{C{sep}} (C{str}).
176 @see: Functions L{pygeodesy.attrs}, L{pygeodesy.pairs} and L{pygeodesy.fstr}
177 '''
178 sep, kwds = _xkwds_pop2(sep_Nones_pairs_kwds, sep=_COMMASPACE_)
179 return sep.join(attrs(self, *names, **kwds))
181 @Property_RO
182 def classname(self):
183 '''Get this object's C{[module.]class} name (C{str}), see
184 property C{.classnaming} and function C{classnaming}.
185 '''
186 return classname(self, prefixed=self._classnaming)
188 @property_doc_(''' the class naming (C{bool}).''')
189 def classnaming(self):
190 '''Get the class naming (C{bool}), see function C{classnaming}.
191 '''
192 return self._classnaming
194 @classnaming.setter # PYCHOK setter!
195 def classnaming(self, prefixed):
196 '''Set the class naming for C{[module.].class} names (C{bool})
197 to C{True} to include the module name.
198 '''
199 b = bool(prefixed)
200 if self._classnaming != b:
201 self._classnaming = b
202 _update_attrs(self, *_Named_Property_ROs)
204 def classof(self, *args, **kwds):
205 '''Create another instance of this very class.
207 @arg args: Optional, positional arguments.
208 @kwarg kwds: Optional, keyword arguments.
210 @return: New instance (B{self.__class__}).
211 '''
212 return _xnamed(self.__class__(*args, **kwds), self.name)
214 def copy(self, deep=False, **name):
215 '''Make a shallow or deep copy of this instance.
217 @kwarg deep: If C{True}, make a deep, otherwise a shallow
218 copy (C{bool}).
219 @kwarg name: Optional, non-empty C{B{name}=NN} (C{str}).
221 @return: The copy (C{This class}).
222 '''
223 c = _xcopy(self, deep=deep)
224 if name:
225 _ = c.rename(name)
226 return c
228 def _DOT_(self, *names):
229 '''(INTERNAL) Period-join C{self.name} and C{names}.
230 '''
231 return _DOT_(self.name, *names)
233 def dup(self, deep=False, **items):
234 '''Duplicate this instance, replacing some attributes.
236 @kwarg deep: If C{True}, duplicate deep, otherwise shallow
237 (C{bool}).
238 @kwarg items: Attributes to be changed (C{any}), including
239 optional C{B{name}} (C{str}).
241 @return: The duplicate (C{This class}).
243 @raise AttributeError: Some B{C{items}} invalid.
244 '''
245 n = self.name
246 m, items = _xkwds_pop2(items, name=n)
247 d = _xdup(self, deep=deep, **items)
248 if m != n:
249 d.rename(m) # zap _Named_Property_ROs
250# if items:
251# _update_all(d)
252 return d
254 def _instr(self, *attrs, **fmt_prec_props_sep_name__kwds):
255 '''(INTERNAL) Format, used by C{Conic}, C{Ellipsoid}, C{Geodesic...}, C{Transform}, C{Triaxial}.
256 '''
257 def _fmt_prec_props_kwds(fmt=Fmt.F, prec=6, props=(), sep=_COMMASPACE_, **kwds):
258 return fmt, prec, props, sep, kwds
260 name, kwds = _name2__(**fmt_prec_props_sep_name__kwds)
261 fmt, prec, props, sep, kwds = _fmt_prec_props_kwds(**kwds)
263 t = () if name is None else (Fmt.EQUAL(name=repr(name or self.name)),)
264 if attrs:
265 t += pairs(((a, getattr(self, a)) for a in attrs),
266 prec=prec, ints=True, fmt=fmt)
267 if props:
268 t += pairs(((p.name, getattr(self, p.name)) for p in props),
269 prec=prec, ints=True)
270 if kwds:
271 t += pairs(kwds, prec=prec)
272 return sep.join(t) if sep else t
274 @property_RO
275 def iteration(self): # see .karney.GDict
276 '''Get the most recent iteration number (C{int}) or C{None}
277 if not available or not applicable.
279 @note: The interation number may be an aggregate number over
280 several, nested functions.
281 '''
282 return self._iteration
284 def methodname(self, which):
285 '''Get a method C{[module.]class.method} name of this object (C{str}).
287 @arg which: The method (C{callable}).
288 '''
289 return _DOT_(self.classname, which.__name__ if callable(which) else _NN_)
291 @property_doc_(''' the name (C{str}).''')
292 def name(self):
293 '''Get the name (C{str}).
294 '''
295 return self._name
297 @name.setter # PYCHOK setter!
298 def name(self, name):
299 '''Set the C{B{name}=NN} (C{str}).
301 @raise NameError: Can't rename, use method L{rename}.
302 '''
303 m, n = self._name, _name__(name)
304 if not m:
305 self._name = n
306 elif n != m:
307 n = repr(n)
308 c = self.classname
309 t = _DOT_(c, Fmt.PAREN(self.rename.__name__, n))
310 n = _DOT_(c, Fmt.EQUALSPACED(name=n))
311 m = Fmt.PAREN(_SPACE_('was', repr(m)))
312 n = _SPACE_(n, m)
313 raise _NameError(n, txt=_SPACE_('use', t))
314 # to set the name from a sub-class, use
315 # self.name = name or
316 # _Named.name.fset(self, name), but NOT
317 # _Named(self).name = name
319 def _name__(self, name): # usually **name
320 '''(INTERNAL) Get the C{name} or this C{name}.
321 '''
322 return _name__(name, _or_nameof=self) # nameof(self)
324 def _name1__(self, kwds):
325 '''(INTERNAL) Resolve and set the C{B{name}=NN}.
326 '''
327 return _name1__(kwds, _or_nameof=self.name) if self.name else kwds
329 @Property_RO
330 def named(self):
331 '''Get the name I{or} class name or C{""} (C{str}).
332 '''
333 return self.name or self.classname
335# @Property_RO
336# def named_(self):
337# '''Get the C{class} name I{and/or} the str(name) or C{""} (C{str}).
338# '''
339# return _xjoined_(self.classname, self.name, enquote=False)
341 @Property_RO
342 def named2(self):
343 '''Get the C{class} name I{and/or} the repr(name) or C{""} (C{str}).
344 '''
345 return _xjoined_(self.classname, self.name)
347 @Property_RO
348 def named3(self):
349 '''Get the I{prefixed} C{class} name I{and/or} the name or C{""} (C{str}).
350 '''
351 return _xjoined_(classname(self, prefixed=True), self.name)
353 @Property_RO
354 def named4(self):
355 '''Get the C{package.module.class} name I{and/or} the name or C{""} (C{str}).
356 '''
357 return _xjoined_(_DOT_(self.__module__, self.__class__.__name__), self.name)
359 def _notImplemented(self, *args, **kwds):
360 '''(INTERNAL) See function L{notImplemented}.
361 '''
362 notImplemented(self, *args, **_xkwds(kwds, up=_UP + 1))
364 def _notOverloaded(self, *args, **kwds):
365 '''(INTERNAL) See function L{notOverloaded}.
366 '''
367 notOverloaded(self, *args, **_xkwds(kwds, up=_UP + 1))
369 def rename(self, name):
370 '''Change the name.
372 @arg name: The new name (C{str}).
374 @return: The previous name (C{str}).
375 '''
376 m, n = self._name, _name__(name)
377 if n != m:
378 self._name = n
379 _update_attrs(self, *_Named_Property_ROs)
380 return m
382 def renamed(self, name):
383 '''Change the name.
385 @arg name: The new name (C{str}).
387 @return: This instance (C{str}).
388 '''
389 _ = self.rename(name)
390 return self
392 @property_RO
393 def sizeof(self):
394 '''Get the current size in C{bytes} of this instance (C{int}).
395 '''
396 return _sizeof(self)
398 def toRepr(self, **unused): # PYCHOK no cover
399 '''Default C{repr(self)}.
400 '''
401 return repr(self)
403 def toStr(self, **unused): # PYCHOK no cover
404 '''Default C{str(self)}.
405 '''
406 return str(self)
408 @deprecated_method
409 def toStr2(self, **kwds): # PYCHOK no cover
410 '''DEPRECATED on 23.10.07, use method C{toRepr}.'''
411 return self.toRepr(**kwds)
413# def _unstr(self, which, *args, **kwds):
414# '''(INTERNAL) Return the string representation of a method
415# invokation of this instance: C{str(self).method(...)}
416#
417# @see: Function L{pygeodesy.unstr}.
418# '''
419# return _DOT_(self, unstr(which, *args, **kwds))
421 def _xnamed(self, inst, name=NN, **force):
422 '''(INTERNAL) Set the instance' C{.name = self.name}.
424 @arg inst: The instance (C{_Named}).
425 @kwarg name: The name (C{str}).
426 @kwarg force: If C{True}, force rename (C{bool}).
428 @return: The B{C{inst}}, renamed if B{C{force}}d
429 or if not named before.
430 '''
431 return _xnamed(inst, name, **force)
433 def _xrenamed(self, inst):
434 '''(INTERNAL) Rename the instance' C{.name = self.name}.
436 @arg inst: The instance (C{_Named}).
438 @return: The B{C{inst}}, named if not named before.
440 @raise TypeError: Not C{isinstance(B{inst}, _Named)}.
441 '''
442 _xinstanceof(_Named, inst=inst) # assert
443 return inst.renamed(self.name)
445_Named_Property_ROs = _allPropertiesOf_n(5, _Named, Property_RO) # PYCHOK once
448class _NamedBase(_Named):
449 '''(INTERNAL) Base class with name.
450 '''
451 def __repr__(self):
452 '''Default C{repr(self)}.
453 '''
454 return self.toRepr()
456 def __str__(self):
457 '''Default C{str(self)}.
458 '''
459 return self.toStr()
461 def others(self, *other, **name_other_up):
462 '''Refined class comparison, invoked as C{.others(other)},
463 C{.others(name=other)} or C{.others(other, name='other')}.
465 @arg other: The other instance (any C{type}).
466 @kwarg name_other_up: Overriding C{name=other} and C{up=1}
467 keyword arguments.
469 @return: The B{C{other}} iff compatible with this instance's
470 C{class} or C{type}.
472 @raise TypeError: Mismatch of the B{C{other}} and this
473 instance's C{class} or C{type}.
474 '''
475 if other: # most common, just one arg B{C{other}}
476 other0 = other[0]
477 if isinstance(other0, self.__class__) or \
478 isinstance(self, other0.__class__):
479 return other0
481 other, name, up = _xother3(self, other, **name_other_up)
482 if isinstance(self, other.__class__) or \
483 isinstance(other, self.__class__):
484 return _xnamed(other, name)
486 raise _xotherError(self, other, name=name, up=up + 1)
488 def toRepr(self, **kwds): # PYCHOK expected
489 '''(INTERNAL) I{Could be overloaded}.
491 @kwarg kwds: Optional, C{toStr} keyword arguments.
493 @return: C{toStr}() with keyword arguments (as C{str}).
494 '''
495 t = lrstrip(self.toStr(**kwds))
496# if self.name:
497# t = NN(Fmt.EQUAL(name=repr(self.name)), sep, t)
498 return Fmt.PAREN(self.classname, t) # XXX (self.named, t)
500# def toRepr(self, **kwds)
501# if kwds:
502# s = NN.join(reprs((self,), **kwds))
503# else: # super().__repr__ only for Python 3+
504# s = super(self.__class__, self).__repr__()
505# return Fmt.PAREN(self.named, s) # clips(s)
507 def toStr(self, **kwds): # PYCHOK no cover
508 '''I{Must be overloaded}.'''
509 notOverloaded(self, **kwds)
511# def toStr(self, **kwds):
512# if kwds:
513# s = NN.join(strs((self,), **kwds))
514# else: # super().__str__ only for Python 3+
515# s = super(self.__class__, self).__str__()
516# return s
518 def _update(self, updated, *attrs, **setters):
519 '''(INTERNAL) Zap cached instance attributes and overwrite C{__dict__} or L{Property_RO} values.
520 '''
521 u = _update_all(self, *attrs) if updated else 0
522 if setters:
523 d = self.__dict__
524 # double-check that setters are Property_RO's
525 for n, v in setters.items():
526 if n in d or _hasProperty(self, n, Property_RO):
527 d[n] = v
528 else:
529 raise _AssertionError(n, v, txt=repr(self))
530 u += len(setters)
531 return u
534class _NamedDict(ADict, _Named):
535 '''(INTERNAL) Named C{dict} with key I{and} attribute access
536 to the items.
537 '''
538 def __init__(self, *args, **kwds):
539 if args: # is args[0] a dict?
540 if len(args) != 1: # or not isinstance(args[0], dict)
541 kwds = _name1__(kwds)
542 t = unstr(self.classname, *args, **kwds) # PYCHOK no cover
543 raise _ValueError(args=len(args), txt=t)
544 kwds = _xkwds(dict(args[0]), **kwds) # args[0] overrides kwds
545 n, kwds = _name2__(**kwds)
546 if n:
547 _Named.name.fset(self, n) # see _Named.name
548 ADict.__init__(self, kwds)
550 def __delattr__(self, name):
551 '''Delete an attribute or item by B{C{name}}.
552 '''
553 if name in self: # in ADict.keys(self):
554 ADict.pop(self, name)
555 elif name in (_name_, _name):
556 # ADict.__setattr__(self, name, NN)
557 _Named.rename(self, NN)
558 else:
559 ADict.__delattr__(self, name)
561 def __getattr__(self, name):
562 '''Get the value of an item by B{C{name}}.
563 '''
564 try:
565 return self[name]
566 except KeyError:
567 if name == _name_:
568 return _Named.name.fget(self)
569 raise ADict._AttributeError(self, self._DOT_(name))
571 def __getitem__(self, key):
572 '''Get the value of an item by B{C{key}}.
573 '''
574 if key == _name_:
575 raise self._KeyError(key)
576 return ADict.__getitem__(self, key)
578 def _KeyError(self, key, *value): # PYCHOK no cover
579 '''(INTERNAL) Create a C{KeyError}.
580 '''
581 n = self.name or self.__class__.__name__
582 t = Fmt.SQUARE(n, key)
583 if value:
584 t = Fmt.EQUALSPACED(t, *value)
585 return _KeyError(t)
587 def __setattr__(self, name, value):
588 '''Set attribute or item B{C{name}} to B{C{value}}.
589 '''
590 if name in self: # in ADict.keys(self)
591 ADict.__setitem__(self, name, value) # self[name] = value
592 else:
593 ADict.__setattr__(self, name, value)
595 def __setitem__(self, key, value):
596 '''Set item B{C{key}} to B{C{value}}.
597 '''
598 if key == _name_:
599 raise self._KeyError(key, repr(value))
600 ADict.__setitem__(self, key, value)
603class _NamedEnum(_NamedDict):
604 '''(INTERNAL) Enum-like C{_NamedDict} with attribute access
605 restricted to valid keys.
606 '''
607 _item_Classes = ()
609 def __init__(self, Class, *Classes, **name):
610 '''New C{_NamedEnum}.
612 @arg Class: Initial class or type acceptable as items
613 values (C{type}).
614 @arg Classes: Additional, acceptable classes or C{type}s.
615 '''
616 self._item_Classes = (Class,) + Classes
617 n = _name__(**name) or NN(Class.__name__, _s_) # _dunder_nameof
618 if n and _xvalid(n, underOK=True):
619 _Named.name.fset(self, n) # see _Named.name
621 def __getattr__(self, name):
622 '''Get the value of an attribute or item by B{C{name}}.
623 '''
624 return _NamedDict.__getattr__(self, name)
626 def __repr__(self):
627 '''Default C{repr(self)}.
628 '''
629 return self.toRepr()
631 def __str__(self):
632 '''Default C{str(self)}.
633 '''
634 return self.toStr()
636 def _assert(self, **kwds):
637 '''(INTERNAL) Check attribute name against given, registered name.
638 '''
639 pypy = _isPyPy()
640 _isa = isinstance
641 for n, v in kwds.items():
642 if _isa(v, _LazyNamedEnumItem): # property
643 assert (n == v.name) if pypy else (n is v.name)
644 # assert not hasattr(self.__class__, n)
645 setattr(self.__class__, n, v)
646 elif _isa(v, self._item_Classes): # PYCHOK no cover
647 assert self[n] is v and getattr(self, n) \
648 and self.find(v) == n
649 else:
650 raise _TypeError(v, name=n)
652 def find(self, item, dflt=None, all=False):
653 '''Find a registered item.
655 @arg item: The item to look for (any C{type}).
656 @kwarg dflt: Value to return if not found (any C{type}).
657 @kwarg all: Use C{True} to search I{all} items or C{False} only
658 the currently I{registered} ones (C{bool}).
660 @return: The B{C{item}}'s name if found (C{str}), or C{{dflt}}
661 if there is no such B{C{item}}.
662 '''
663 for k, v in self.items(all=all): # or ADict.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 I{registered} item 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 I{all} items or C{False} for
684 only the currently I{registered} ones (C{bool}).
685 @kwarg asorted: If C{True}, yield the items in I{alphabetical,
686 case-insensitive} order (C{bool}).
687 '''
688 if all: # instantiate any remaining L{_LazyNamedEnumItem}
689 _isa = isinstance
690 for n, p in tuple(self.__class__.__dict__.items()):
691 if _isa(p, _LazyNamedEnumItem):
692 _ = getattr(self, n)
693 return itemsorted(self) if asorted else ADict.items(self)
695 def keys(self, **all_asorted):
696 '''Yield the name (C{str}) of I{all} or only the currently I{registered}
697 items, optionally sorted I{alphabetically, 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} currently I{registed} item.
707 @return: The removed item.
708 '''
709 return self._zapitem(*ADict.popitem(self))
711 def register(self, item):
712 '''Registed one new item or I{all} or I{any} unregistered ones.
714 @arg item: The item (any C{type}) or B{I{all}} or B{C{any}}.
716 @return: The item name (C{str}) or C("all") or C{"any"}.
718 @raise NameError: An B{C{item}} with that name is already
719 registered the B{C{item}} has no or an
720 invalid name.
722 @raise TypeError: The B{C{item}} type invalid.
723 '''
724 if item is all or item is any:
725 _ = self.items(all=True)
726 n = item.__name__
727 else:
728 try:
729 n = item.name
730 if not (n and isstr(n) and isidentifier(n)):
731 raise ValueError()
732 except (AttributeError, ValueError, TypeError) as x:
733 n = _DOT_(_item_, _name_)
734 raise _NameError(n, item, cause=x)
735 if n in self:
736 t = _SPACE_(_item_, self._DOT_(n), _exists_)
737 raise _NameError(t, txt=repr(item))
738 if not isinstance(item, self._item_Classes): # _xinstanceof
739 n = self._DOT_(n)
740 raise _TypesError(n, item, *self._item_Classes)
741 self[n] = item
742 return n
744 def unregister(self, name_or_item):
745 '''Remove a I{registered} item.
747 @arg name_or_item: Name (C{str}) or the item (any C{type}).
749 @return: The unregistered item.
751 @raise AttributeError: No such B{C{item}}.
753 @raise NameError: No item with that B{C{name}}.
754 '''
755 if isstr(name_or_item):
756 name = name_or_item
757 else:
758 name = self.find(name_or_item, dflt=MISSING) # all=True?
759 if name is MISSING:
760 t = _SPACE_(_no_, _such_, self.classname, _item_)
761 raise _AttributeError(t, txt=repr(name_or_item))
762 try:
763 item = ADict.pop(self, name)
764 except KeyError:
765 raise _NameError(item=self._DOT_(name), txt=_doesn_t_exist_)
766 return self._zapitem(name, item)
768 pop = unregister
770 def toRepr(self, prec=6, fmt=Fmt.F, sep=_COMMANL_, **all_asorted): # PYCHOK _NamedDict, ADict
771 '''Like C{repr(dict)} but C{name}s optionally sorted and
772 C{floats} formatted by function L{pygeodesy.fstr}.
773 '''
774 t = ((self._DOT_(n), v) for n, v in self.items(**all_asorted))
775 return sep.join(pairs(t, prec=prec, fmt=fmt, sep=_COLONSPACE_))
777 def toStr(self, *unused, **all_asorted): # PYCHOK _NamedDict, ADict
778 '''Return a string with all C{name}s, optionally sorted.
779 '''
780 return self._DOT_(_COMMASPACEDOT_.join(self.keys(**all_asorted)))
782 def values(self, **all_asorted):
783 '''Yield the value (C{type}) of all or only the I{registered} items,
784 optionally sorted I{alphabetically} and I{case-insensitively}.
786 @kwarg all_asorted: See method C{items}.
787 '''
788 for _, v in self.items(**all_asorted):
789 yield v
791 def _zapitem(self, name, item):
792 # remove _LazyNamedEnumItem property value if still present
793 if self.__dict__.get(name, None) is item:
794 self.__dict__.pop(name) # [name] = None
795 item._enum = None
796 return item
799class _LazyNamedEnumItem(property_RO): # XXX or descriptor?
800 '''(INTERNAL) Lazily instantiated L{_NamedEnumItem}.
801 '''
802 pass
805def _lazyNamedEnumItem(name, *args, **kwds):
806 '''(INTERNAL) L{_LazyNamedEnumItem} property-like factory.
808 @see: Luciano Ramalho, "Fluent Python", O'Reilly, Example
809 19-24, 2016 p. 636 or Example 22-28, 2022 p. 869+
810 '''
811 def _fget(inst):
812 # assert isinstance(inst, _NamedEnum)
813 try: # get the item from the instance' __dict__
814 # item = inst.__dict__[name] # ... or ADict
815 item = inst[name]
816 except KeyError:
817 # instantiate an _NamedEnumItem, it self-registers
818 item = inst._Lazy(*args, **_xkwds(kwds, name=name))
819 # assert inst[name] is item # MUST be registered
820 # store the item in the instance' __dict__ ...
821 # inst.__dict__[name] = item # ... or update the
822 inst.update({name: item}) # ... ADict for Triaxials
823 # remove the property from the registry class, such that
824 # (a) the property no longer overrides the instance' item
825 # in inst.__dict__ and (b) _NamedEnum.items(all=True) only
826 # sees any un-instantiated ones yet to be instantiated
827 p = getattr(inst.__class__, name, None)
828 if isinstance(p, _LazyNamedEnumItem):
829 delattr(inst.__class__, name)
830 # assert isinstance(item, _NamedEnumItem)
831 return item
833 p = _LazyNamedEnumItem(_fget)
834 p.name = name
835 return p
838class _NamedEnumItem(_NamedBase):
839 '''(INTERNAL) Base class for items in a C{_NamedEnum} registery.
840 '''
841 _enum = None
843# def __ne__(self, other): # XXX fails for Lcc.conic = conic!
844# '''Compare this and an other item.
845#
846# @return: C{True} if different, C{False} otherwise.
847# '''
848# return not self.__eq__(other)
850 @property_doc_(''' the I{registered} name (C{str}).''')
851 def name(self):
852 '''Get the I{registered} name (C{str}).
853 '''
854 return self._name
856 @name.setter # PYCHOK setter!
857 def name(self, name):
858 '''Set the name, unless already registered (C{str}).
859 '''
860 name = _name__(name) or _NN_
861 if self._enum:
862 raise _NameError(name, self, txt=_registered_) # _TypeError
863 if name:
864 self._name = name
866 def _register(self, enum, name):
867 '''(INTERNAL) Add this item as B{C{enum.name}}.
869 @note: Don't register if name is empty or doesn't
870 start with a letter.
871 '''
872 name = _name__(name)
873 if name and _xvalid(name, underOK=True):
874 self.name = name
875 if name[:1].isalpha(): # '_...' not registered
876 enum.register(self)
877 self._enum = enum
879 def unregister(self):
880 '''Remove this instance from its C{_NamedEnum} registry.
882 @raise AssertionError: Mismatch of this and registered item.
884 @raise NameError: This item is unregistered.
885 '''
886 enum = self._enum
887 if enum and self.name and self.name in enum:
888 item = enum.unregister(self.name)
889 if item is not self: # PYCHOK no cover
890 t = _SPACE_(repr(item), _vs_, repr(self))
891 raise _AssertionError(t)
894# from pygeodesy.props import _NamedProperty
897class _NamedTuple(tuple, _Named):
898 '''(INTERNAL) Base for named C{tuple}s with both index I{and}
899 attribute name access to the items.
901 @note: This class is similar to Python's C{namedtuple},
902 but statically defined, lighter and limited.
903 '''
904 _Names_ = () # item names, non-identifier, no leading underscore
905 '''Tuple specifying the C{name} of each C{Named-Tuple} item.
907 @note: Specify at least 2 item names.
908 '''
909 _Units_ = () # .units classes
910 '''Tuple defining the C{units} of the value of each C{Named-Tuple} item.
912 @note: The C{len(_Units_)} must match C{len(_Names_)}.
913 '''
914 _validated = False # set to True I{per sub-class!}
916 def __new__(cls, arg, *args, **iteration_name):
917 '''New L{_NamedTuple} initialized with B{C{positional}} arguments.
919 @arg arg: Tuple items (C{tuple}, C{list}, ...) or first tuple
920 item of several more in other positional arguments.
921 @arg args: Tuple items (C{any}), all positional arguments.
922 @kwarg iteration_name: Only keyword arguments C{B{iteration}=None}
923 and C{B{name}=NN} are used, any other are
924 I{silently} ignored.
926 @raise LenError: Unequal number of positional arguments and
927 number of item C{_Names_} or C{_Units_}.
929 @raise TypeError: The C{_Names_} or C{_Units_} attribute is
930 not a C{tuple} of at least 2 items.
932 @raise ValueError: Item name is not a C{str} or valid C{identifier}
933 or starts with C{underscore}.
934 '''
935 n, args = len2(((arg,) + args) if args else arg)
936 self = tuple.__new__(cls, args)
937 if not self._validated:
938 self._validate()
940 N = len(self._Names_)
941 if n != N:
942 raise LenError(self.__class__, args=n, _Names_=N)
944 if iteration_name:
945 i, name = _xkwds_pop2(iteration_name, iteration=None)
946 if i is not None:
947 self._iteration = i
948 if name:
949 self.name = name
950 return self
952 def __delattr__(self, name):
953 '''Delete an attribute by B{C{name}}.
955 @note: Items can not be deleted.
956 '''
957 if name in self._Names_:
958 t = _SPACE_(_del_, self._DOT_(name))
959 raise _TypeError(t, txt=_immutable_)
960 elif name in (_name_, _name):
961 _Named.__setattr__(self, name, NN) # XXX _Named.name.fset(self, NN)
962 else:
963 tuple.__delattr__(self, name)
965 def __getattr__(self, name):
966 '''Get the value of an attribute or item by B{C{name}}.
967 '''
968 try:
969 return tuple.__getitem__(self, self._Names_.index(name))
970 except IndexError as x:
971 raise _IndexError(self._DOT_(name), cause=x)
972 except ValueError: # e.g. _iteration
973 return tuple.__getattr__(self, name) # __getattribute__
975# def __getitem__(self, index): # index, slice, etc.
976# '''Get the item(s) at an B{C{index}} or slice.
977# '''
978# return tuple.__getitem__(self, index)
980 def __hash__(self):
981 return tuple.__hash__(self)
983 def __repr__(self):
984 '''Default C{repr(self)}.
985 '''
986 return self.toRepr()
988 def __setattr__(self, name, value):
989 '''Set attribute or item B{C{name}} to B{C{value}}.
990 '''
991 if name in self._Names_:
992 t = Fmt.EQUALSPACED(self._DOT_(name), repr(value))
993 raise _TypeError(t, txt=_immutable_)
994 elif name in (_name_, _name):
995 _Named.__setattr__(self, name, value) # XXX _Named.name.fset(self, value)
996 else: # e.g. _iteration
997 tuple.__setattr__(self, name, value)
999 def __str__(self):
1000 '''Default C{repr(self)}.
1001 '''
1002 return self.toStr()
1004 def _DOT_(self, *names):
1005 '''(INTERNAL) Period-join C{self.classname} and C{names}.
1006 '''
1007 return _DOT_(self.classname, *names)
1009 def dup(self, name=NN, **items):
1010 '''Duplicate this tuple replacing one or more items.
1012 @kwarg name: Optional new name (C{str}).
1013 @kwarg items: Items to be replaced (C{name=value} pairs), if any.
1015 @return: A copy of this tuple with B{C{items}}.
1017 @raise NameError: Some B{C{items}} invalid.
1018 '''
1019 t = list(self)
1020 U = self._Units_
1021 if items:
1022 _ix = self._Names_.index
1023 _2U = _MODS.units._toUnit
1024 try:
1025 for n, v in items.items():
1026 i = _ix(n)
1027 t[i] = _2U(U[i], v, name=n)
1028 except ValueError: # bad item name
1029 raise _NameError(self._DOT_(n), v, this=self)
1030 return self.classof(*t).reUnit(*U, name=name)
1032 def items(self):
1033 '''Yield the items, each as a C{(name, value)} pair (C{2-tuple}).
1035 @see: Method C{.units}.
1036 '''
1037 for n, v in _zip(self._Names_, self): # strict=True
1038 yield n, v
1040 iteritems = items
1042 def reUnit(self, *Units, **name):
1043 '''Replace some of this C{Named-Tuple}'s C{Units}.
1045 @arg Units: One or more C{Unit} classes, all positional.
1046 @kwarg name: Optional C{B{name}=NN} (C{str}).
1048 @return: This instance with updated C{Units}.
1050 @note: This C{Named-Tuple}'s values are I{not updated}.
1051 '''
1052 U = self._Units_
1053 n = min(len(U), len(Units))
1054 if n:
1055 R = Units + U[n:]
1056 if R != U:
1057 self._Units_ = R
1058 return self.renamed(name) if name else self
1060 def toRepr(self, prec=6, sep=_COMMASPACE_, fmt=Fmt.F, **unused): # PYCHOK signature
1061 '''Return this C{Named-Tuple} items as C{name=value} string(s).
1063 @kwarg prec: The C{float} precision, number of decimal digits (0..9).
1064 Trailing zero decimals are stripped for B{C{prec}} values
1065 of 1 and above, but kept for negative B{C{prec}} values.
1066 @kwarg sep: Separator to join (C{str}).
1067 @kwarg fmt: Optional C{float} format (C{letter}).
1069 @return: Tuple items (C{str}).
1070 '''
1071 t = pairs(self.items(), prec=prec, fmt=fmt)
1072# if self.name:
1073# t = (Fmt.EQUAL(name=repr(self.name)),) + t
1074 return Fmt.PAREN(self.named, sep.join(t)) # XXX (self.classname, sep.join(t))
1076 def toStr(self, prec=6, sep=_COMMASPACE_, fmt=Fmt.F, **unused): # PYCHOK signature
1077 '''Return this C{Named-Tuple} items as string(s).
1079 @kwarg prec: The C{float} precision, number of decimal digits (0..9).
1080 Trailing zero decimals are stripped for B{C{prec}} values
1081 of 1 and above, but kept for negative B{C{prec}} values.
1082 @kwarg sep: Separator to join (C{str}).
1083 @kwarg fmt: Optional C{float} format (C{letter}).
1085 @return: Tuple items (C{str}).
1086 '''
1087 return Fmt.PAREN(sep.join(reprs(self, prec=prec, fmt=fmt)))
1089 def toUnits(self, Error=UnitError, **name): # overloaded in .frechet, .hausdorff
1090 '''Return a copy of this C{Named-Tuple} with each item value wrapped
1091 as an instance of its L{units} class.
1093 @kwarg Error: Error to raise for L{units} issues (C{UnitError}).
1094 @kwarg name: Optional C{B{name}=NN} (C{str}).
1096 @return: A duplicate of this C{Named-Tuple} (C{C{Named-Tuple}}).
1098 @raise Error: Invalid C{Named-Tuple} item or L{units} class.
1099 '''
1100 t = tuple(v for _, v in self.units(Error=Error))
1101 return self.classof(*t).reUnit(*self._Units_, **name)
1103 def units(self, **Error):
1104 '''Yield the items, each as a C{2-tuple (name, value}) with the
1105 value wrapped as an instance of its L{units} class.
1107 @kwarg Error: Optional C{B{Error}=UnitError} to raise.
1109 @raise Error: Invalid C{Named-Tuple} item or L{units} class.
1111 @see: Method C{.items}.
1112 '''
1113 _2U = _MODS.units._toUnit
1114 for n, v, U in _zip(self._Names_, self, self._Units_): # strict=True
1115 yield n, _2U(U, v, name=n, **Error)
1117 iterunits = units
1119 def _validate(self, underOK=False): # see .EcefMatrix
1120 '''(INTERNAL) One-time check of C{_Names_} and C{_Units_}
1121 for each C{_NamedUnit} I{sub-class separately}.
1122 '''
1123 ns = self._Names_
1124 if not (isinstance(ns, tuple) and len(ns) > 1): # XXX > 0
1125 raise _TypeError(self._DOT_(_Names_), ns)
1126 for i, n in enumerate(ns):
1127 if not _xvalid(n, underOK=underOK):
1128 t = Fmt.SQUARE(_Names_=i) # PYCHOK no cover
1129 raise _ValueError(self._DOT_(t), n)
1131 us = self._Units_
1132 if not isinstance(us, tuple):
1133 raise _TypeError(self._DOT_(_Units_), us)
1134 if len(us) != len(ns):
1135 raise LenError(self.__class__, _Units_=len(us), _Names_=len(ns))
1136 for i, u in enumerate(us):
1137 if not (u is None or callable(u)):
1138 t = Fmt.SQUARE(_Units_=i) # PYCHOK no cover
1139 raise _TypeError(self._DOT_(t), u)
1141 self.__class__._validated = True
1143 def _xtend(self, xTuple, *items, **name):
1144 '''(INTERNAL) Extend this C{Named-Tuple} with C{items} to an other B{C{xTuple}}.
1145 '''
1146 _xsubclassof(_NamedTuple, xTuple=xTuple)
1147 if len(xTuple._Names_) != (len(self._Names_) + len(items)) or \
1148 xTuple._Names_[:len(self)] != self._Names_: # PYCHOK no cover
1149 c = NN(self.classname, repr(self._Names_))
1150 x = NN(xTuple.__name__, repr(xTuple._Names_))
1151 raise TypeError(_SPACE_(c, _vs_, x))
1152 t = self + items
1153 return xTuple(t, name=self._name__(name)) # .reUnit(*self._Units_)
1156def callername(up=1, dflt=NN, source=False, underOK=False):
1157 '''Get the name of the invoking callable.
1159 @kwarg up: Number of call stack frames up (C{int}).
1160 @kwarg dflt: Default return value (C{any}).
1161 @kwarg source: Include source file name and line number (C{bool}).
1162 @kwarg underOK: If C{True}, private, internal callables are OK,
1163 otherwise private callables are skipped (C{bool}).
1165 @return: The callable name (C{str}) or B{C{dflt}} if none found.
1166 '''
1167 try: # see .lazily._caller3
1168 for u in range(up, up + 32):
1169 n, f, s = _caller3(u)
1170 if n and (underOK or n.startswith(_DUNDER_) or
1171 not n.startswith(_UNDER_)):
1172 if source:
1173 n = NN(n, _AT_, f, _COLON_, str(s))
1174 return n
1175 except (AttributeError, ValueError):
1176 pass
1177 return dflt
1180def _callername2(args, callername=NN, source=False, underOK=False, up=_UP, **kwds):
1181 '''(INTERNAL) Extract C{callername}, C{source}, C{underOK} and C{up} from C{kwds}.
1182 '''
1183 n = callername or _MODS.named.callername(up=up + 1, source=source,
1184 underOK=underOK or bool(args or kwds))
1185 return n, kwds
1188def _callname(name, class_name, self_name, up=1):
1189 '''(INTERNAL) Assemble the name for an invokation.
1190 '''
1191 n, c = class_name, callername(up=up + 1)
1192 if c:
1193 n = _DOT_(n, Fmt.PAREN(c, name))
1194 if self_name:
1195 n = _SPACE_(n, repr(self_name))
1196 return n
1199def classname(inst, prefixed=None):
1200 '''Return the instance' class name optionally prefixed with the
1201 module name.
1203 @arg inst: The object (any C{type}).
1204 @kwarg prefixed: Include the module name (C{bool}), see
1205 function C{classnaming}.
1207 @return: The B{C{inst}}'s C{[module.]class} name (C{str}).
1208 '''
1209 if prefixed is None:
1210 prefixed = getattr(inst, classnaming.__name__, prefixed)
1211 return modulename(inst.__class__, prefixed=prefixed)
1214def classnaming(prefixed=None):
1215 '''Get/set the default class naming for C{[module.]class} names.
1217 @kwarg prefixed: Include the module name (C{bool}).
1219 @return: Previous class naming setting (C{bool}).
1220 '''
1221 t = _Named._classnaming
1222 if prefixed in (True, False):
1223 _Named._classnaming = prefixed
1224 return t
1227def modulename(clas, prefixed=None): # in .basics._xversion
1228 '''Return the class name optionally prefixed with the
1229 module name.
1231 @arg clas: The class (any C{class}).
1232 @kwarg prefixed: Include the module name (C{bool}), see
1233 function C{classnaming}.
1235 @return: The B{C{class}}'s C{[module.]class} name (C{str}).
1236 '''
1237 try:
1238 n = clas.__name__
1239 except AttributeError:
1240 n = clas if isstr(clas) else _dunder_name_
1241 if prefixed or (classnaming() if prefixed is None else False):
1242 try:
1243 m = clas.__module__.rsplit(_DOT_, 1)
1244 n = _DOT_.join(m[1:] + [n])
1245 except AttributeError:
1246 pass
1247 return n
1250# def _name__(name=NN, name__=None, _or_nameof=None, **kwds):
1251# '''(INTERNAL) Get single keyword argument C{B{name}=NN|None}.
1252# '''
1253# if kwds: # "unexpected keyword arguments ..."
1254# m = _MODS.errors
1255# raise m._UnexpectedError(**kwds)
1256# if name: # is given
1257# n = _name__(**name) if isinstance(name, dict) else str(name)
1258# elif name__ is not None:
1259# n = getattr(name__, _dunder_name_, NN) # _xattr(name__, __name__=NN)
1260# else:
1261# n = name # NN or None or {} or any False type
1262# if _or_nameof is not None and not n:
1263# n = getattr(_or_nameof, _name_, NN) # _xattr(_or_nameof, name=NN)
1264# return n # str or None or {}
1267def _name__(name=NN, **kwds):
1268 '''(INTERNAL) Get single keyword argument C{B{name}=NN|None}.
1269 '''
1270 if name or kwds:
1271 name, kwds = _name2__(name, **kwds)
1272 if kwds: # "unexpected keyword arguments ..."
1273 raise _UnexpectedError(**kwds)
1274 return name if name or name is None else NN
1277def _name1__(kwds_name, **name__or_nameof):
1278 '''(INTERNAL) Resolve and set the C{B{name}=NN}.
1279 '''
1280 if kwds_name or name__or_nameof:
1281 n, kwds_name = _name2__(kwds_name, **name__or_nameof)
1282 kwds_name.update(name=n)
1283 return kwds_name
1286def _name2__(name=NN, name__=None, _or_nameof=None, **kwds):
1287 '''(INTERNAL) Get the C{B{name}=NN|None} and other C{kwds}.
1288 '''
1289 if name: # is given
1290 if isinstance(name, dict):
1291 kwds.update(name) # kwds = _xkwds(kwds, **name)?
1292 n, kwds = _name2__(**kwds)
1293 else:
1294 n = str(name)
1295 elif name__ is not None:
1296 n = _dunder_nameof(name__, NN)
1297 else:
1298 n = name if name is None else NN
1299 if _or_nameof is not None and not n:
1300 n = _xattr(_or_nameof, name=NN) # nameof
1301 return n, kwds # (str or None or {}), dict
1304def nameof(inst):
1305 '''Get the name of an instance.
1307 @arg inst: The object (any C{type}).
1309 @return: The instance' name (C{str}) or C{""}.
1310 '''
1311 n = _xattr(inst, name=NN)
1312 if not n: # and isinstance(inst, property):
1313 try:
1314 n = inst.fget.__name__
1315 except AttributeError:
1316 n = NN
1317 return n
1320def _notDecap(where):
1321 '''De-Capitalize C{where.__name__}.
1322 '''
1323 n = where.__name__
1324 c = n[3].lower() # len(_not_)
1325 return NN(n[:3], _SPACE_, c, n[4:])
1328def _notError(inst, name, args, kwds): # PYCHOK no cover
1329 '''(INTERNAL) Format an error message.
1330 '''
1331 n = _DOT_(classname(inst, prefixed=True), _dunder_nameof(name, name))
1332 m = _COMMASPACE_.join(modulename(c, prefixed=True) for c in inst.__class__.__mro__[1:-1])
1333 return _COMMASPACE_(unstr(n, *args, **kwds), Fmt.PAREN(_MRO_, m))
1336def _NotImplemented(inst, *other, **kwds):
1337 '''(INTERNAL) Raise a C{__special__} error or return C{NotImplemented},
1338 but only if env variable C{PYGEODESY_NOTIMPLEMENTED=std}.
1339 '''
1340 if _std_NotImplemented:
1341 return NotImplemented
1342 n, kwds = _callername2(other, **kwds) # source=True
1343 t = unstr(_DOT_(classname(inst), n), *other, **kwds)
1344 raise _NotImplementedError(t, txt=repr(inst))
1347def notImplemented(inst, *args, **kwds): # PYCHOK no cover
1348 '''Raise a C{NotImplementedError} for a missing instance method or
1349 property or for a missing caller feature.
1351 @arg inst: Caller instance (C{any}) or C{None} for function.
1352 @arg args: Method or property positional arguments (any C{type}s).
1353 @arg kwds: Method or property keyword arguments (any C{type}s),
1354 except C{B{callername}=NN}, C{B{underOK}=False} and
1355 C{B{up}=2}.
1356 '''
1357 n, kwds = _callername2(args, **kwds)
1358 t = _notError(inst, n, args, kwds) if inst else unstr(n, *args, **kwds)
1359 raise _NotImplementedError(t, txt=_notDecap(notImplemented))
1362def notOverloaded(inst, *args, **kwds): # PYCHOK no cover
1363 '''Raise an C{AssertionError} for a method or property not overloaded.
1365 @arg inst: Instance (C{any}).
1366 @arg args: Method or property positional arguments (any C{type}s).
1367 @arg kwds: Method or property keyword arguments (any C{type}s),
1368 except C{B{callername}=NN}, C{B{underOK}=False} and
1369 C{B{up}=2}.
1370 '''
1371 n, kwds = _callername2(args, **kwds)
1372 t = _notError(inst, n, args, kwds)
1373 raise _AssertionError(t, txt=_notDecap(notOverloaded))
1376def _Pass(arg, **unused): # PYCHOK no cover
1377 '''(INTERNAL) I{Pass-thru} class for C{_NamedTuple._Units_}.
1378 '''
1379 return arg
1382def _xjoined_(prefix, name=NN, enquote=True, **name__or_nameof):
1383 '''(INTERNAL) Join C{prefix} and non-empty C{name}.
1384 '''
1385 if name__or_nameof:
1386 name = _name__(name, **name__or_nameof)
1387 if name and prefix:
1388 if enquote:
1389 name = repr(name)
1390 t = _SPACE_(prefix, name)
1391 else:
1392 t = prefix or name
1393 return t
1396def _xnamed(inst, name=NN, force=False, **name__or_nameof):
1397 '''(INTERNAL) Set the instance' C{.name = B{name}}.
1399 @arg inst: The instance (C{_Named}).
1400 @kwarg name: The name (C{str}).
1401 @kwarg force: If C{True}, force rename (C{bool}).
1403 @return: The B{C{inst}}, renamed if B{C{force}}d
1404 or if not named before.
1405 '''
1406 if name__or_nameof:
1407 name = _name__(name, **name__or_nameof)
1408 if name and isinstance(inst, _Named):
1409 if not inst.name:
1410 inst.name = name
1411 elif force:
1412 inst.rename(name)
1413 return inst
1416def _xother3(inst, other, name=_other_, up=1, **name_other):
1417 '''(INTERNAL) Get C{name} and C{up} for a named C{other}.
1418 '''
1419 if name_other: # and other is None
1420 name, other = _xkwds_item2(name_other)
1421 elif other and len(other) == 1:
1422 name, other = _name__(name), other[0]
1423 else:
1424 raise _AssertionError(name, other, txt=classname(inst, prefixed=True))
1425 return other, name, up
1428def _xotherError(inst, other, name=_other_, up=1):
1429 '''(INTERNAL) Return a C{_TypeError} for an incompatible, named C{other}.
1430 '''
1431 n = _callname(name, classname(inst, prefixed=True), inst.name, up=up + 1)
1432 return _TypeError(name, other, txt=_incompatible(n))
1435def _xvalid(name, underOK=False):
1436 '''(INTERNAL) Check valid attribute name C{name}.
1437 '''
1438 return bool(name and isstr(name)
1439 and name != _name_
1440 and (underOK or not name.startswith(_UNDER_))
1441 and (not iskeyword(name))
1442 and isidentifier(name))
1445__all__ += _ALL_DOCS(_Named,
1446 _NamedBase, # _NamedDict,
1447 _NamedEnum, _NamedEnumItem,
1448 _NamedTuple)
1450# **) MIT License
1451#
1452# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
1453#
1454# Permission is hereby granted, free of charge, to any person obtaining a
1455# copy of this software and associated documentation files (the "Software"),
1456# to deal in the Software without restriction, including without limitation
1457# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1458# and/or sell copies of the Software, and to permit persons to whom the
1459# Software is furnished to do so, subject to the following conditions:
1460#
1461# The above copyright notice and this permission notice shall be included
1462# in all copies or substantial portions of the Software.
1463#
1464# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1465# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1466# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1467# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1468# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1469# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1470# OTHER DEALINGS IN THE SOFTWARE.