Coverage for pygeodesy/named.py: 96%
523 statements
« prev ^ index » next coverage.py v7.6.0, created at 2024-08-02 18:24 -0400
« prev ^ index » next coverage.py v7.6.0, created at 2024-08-02 18:24 -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.07.12'
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
218 a shallow 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 @kwarg items: Attributes to be changed (C{any}), including
238 optional C{B{name}} (C{str}).
240 @return: The duplicate (C{This class}).
242 @raise AttributeError: Some B{C{items}} invalid.
243 '''
244 n = self.name
245 m, items = _xkwds_pop2(items, name=n)
246 d = _xdup(self, deep=deep, **items)
247 if m != n:
248 d.rename(m) # zap _Named_Property_ROs
249# if items:
250# _update_all(d)
251 return d
253 def _instr(self, *attrs, **fmt_prec_props_sep_name__kwds):
254 '''(INTERNAL) Format, used by C{Conic}, C{Ellipsoid}, C{Geodesic...}, C{Transform}, C{Triaxial}.
255 '''
256 def _fmt_prec_props_kwds(fmt=Fmt.F, prec=6, props=(), sep=_COMMASPACE_, **kwds):
257 return fmt, prec, props, sep, kwds
259 name, kwds = _name2__(**fmt_prec_props_sep_name__kwds)
260 fmt, prec, props, sep, kwds = _fmt_prec_props_kwds(**kwds)
262 t = () if name is None else (Fmt.EQUAL(name=repr(name or self.name)),)
263 if attrs:
264 t += pairs(((a, getattr(self, a)) for a in attrs),
265 prec=prec, ints=True, fmt=fmt)
266 if props:
267 t += pairs(((p.name, getattr(self, p.name)) for p in props),
268 prec=prec, ints=True)
269 if kwds:
270 t += pairs(kwds, prec=prec)
271 return sep.join(t) if sep else t
273 @property_RO
274 def iteration(self): # see .karney.GDict
275 '''Get the most recent iteration number (C{int}) or C{None}
276 if not available or not applicable.
278 @note: The interation number may be an aggregate number over
279 several, nested functions.
280 '''
281 return self._iteration
283 def methodname(self, which):
284 '''Get a method C{[module.]class.method} name of this object (C{str}).
286 @arg which: The method (C{callable}).
287 '''
288 return _DOT_(self.classname, which.__name__ if callable(which) else _NN_)
290 @property_doc_(''' the name (C{str}).''')
291 def name(self):
292 '''Get the name (C{str}).
293 '''
294 return self._name
296 @name.setter # PYCHOK setter!
297 def name(self, name):
298 '''Set the C{B{name}=NN} (C{str}).
300 @raise NameError: Can't rename, use method L{rename}.
301 '''
302 m, n = self._name, _name__(name)
303 if not m:
304 self._name = n
305 elif n != m:
306 n = repr(n)
307 c = self.classname
308 t = _DOT_(c, Fmt.PAREN(self.rename.__name__, n))
309 n = _DOT_(c, Fmt.EQUALSPACED(name=n))
310 m = Fmt.PAREN(_SPACE_('was', repr(m)))
311 n = _SPACE_(n, m)
312 raise _NameError(n, txt=_SPACE_('use', t))
313 # to set the name from a sub-class, use
314 # self.name = name or
315 # _Named.name.fset(self, name), but NOT
316 # _Named(self).name = name
318 def _name__(self, name): # usually **name
319 '''(INTERNAL) Get the C{name} or this C{name}.
320 '''
321 return _name__(name, _or_nameof=self) # nameof(self)
323 def _name1__(self, kwds):
324 '''(INTERNAL) Resolve and set the C{B{name}=NN}.
325 '''
326 return _name1__(kwds, _or_nameof=self.name) if self.name else kwds
328 @Property_RO
329 def named(self):
330 '''Get the name I{or} class name or C{""} (C{str}).
331 '''
332 return self.name or self.classname
334# @Property_RO
335# def named_(self):
336# '''Get the C{class} name I{and/or} the str(name) or C{""} (C{str}).
337# '''
338# return _xjoined_(self.classname, self.name, enquote=False)
340 @Property_RO
341 def named2(self):
342 '''Get the C{class} name I{and/or} the repr(name) or C{""} (C{str}).
343 '''
344 return _xjoined_(self.classname, self.name)
346 @Property_RO
347 def named3(self):
348 '''Get the I{prefixed} C{class} name I{and/or} the name or C{""} (C{str}).
349 '''
350 return _xjoined_(classname(self, prefixed=True), self.name)
352 @Property_RO
353 def named4(self):
354 '''Get the C{package.module.class} name I{and/or} the name or C{""} (C{str}).
355 '''
356 return _xjoined_(_DOT_(self.__module__, self.__class__.__name__), self.name)
358 def _notImplemented(self, *args, **kwds):
359 '''(INTERNAL) See function L{notImplemented}.
360 '''
361 notImplemented(self, *args, **_xkwds(kwds, up=_UP + 1))
363 def _notOverloaded(self, *args, **kwds):
364 '''(INTERNAL) See function L{notOverloaded}.
365 '''
366 notOverloaded(self, *args, **_xkwds(kwds, up=_UP + 1))
368 def rename(self, name):
369 '''Change the name.
371 @arg name: The new name (C{str}).
373 @return: The previous name (C{str}).
374 '''
375 m, n = self._name, _name__(name)
376 if n != m:
377 self._name = n
378 _update_attrs(self, *_Named_Property_ROs)
379 return m
381 def renamed(self, name):
382 '''Change the name.
384 @arg name: The new name (C{str}).
386 @return: This instance (C{str}).
387 '''
388 _ = self.rename(name)
389 return self
391 @property_RO
392 def sizeof(self):
393 '''Get the current size in C{bytes} of this instance (C{int}).
394 '''
395 return _sizeof(self)
397 def toRepr(self, **unused): # PYCHOK no cover
398 '''Default C{repr(self)}.
399 '''
400 return repr(self)
402 def toStr(self, **unused): # PYCHOK no cover
403 '''Default C{str(self)}.
404 '''
405 return str(self)
407 @deprecated_method
408 def toStr2(self, **kwds): # PYCHOK no cover
409 '''DEPRECATED on 23.10.07, use method C{toRepr}.'''
410 return self.toRepr(**kwds)
412# def _unstr(self, which, *args, **kwds):
413# '''(INTERNAL) Return the string representation of a method
414# invokation of this instance: C{str(self).method(...)}
415#
416# @see: Function L{pygeodesy.unstr}.
417# '''
418# return _DOT_(self, unstr(which, *args, **kwds))
420 def _xnamed(self, inst, name=NN, **force):
421 '''(INTERNAL) Set the instance' C{.name = self.name}.
423 @arg inst: The instance (C{_Named}).
424 @kwarg name: The name (C{str}).
425 @kwarg force: If C{True}, force rename (C{bool}).
427 @return: The B{C{inst}}, renamed if B{C{force}}d
428 or if not named before.
429 '''
430 return _xnamed(inst, name, **force)
432 def _xrenamed(self, inst):
433 '''(INTERNAL) Rename the instance' C{.name = self.name}.
435 @arg inst: The instance (C{_Named}).
437 @return: The B{C{inst}}, named if not named before.
439 @raise TypeError: Not C{isinstance(B{inst}, _Named)}.
440 '''
441 _xinstanceof(_Named, inst=inst) # assert
442 return inst.renamed(self.name)
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 others(self, *other, **name_other_up):
461 '''Refined class comparison, invoked as C{.others(other)},
462 C{.others(name=other)} or C{.others(other, name='other')}.
464 @arg other: The other instance (any C{type}).
465 @kwarg name_other_up: Overriding C{name=other} and C{up=1}
466 keyword arguments.
468 @return: The B{C{other}} iff compatible with this instance's
469 C{class} or C{type}.
471 @raise TypeError: Mismatch of the B{C{other}} and this
472 instance's C{class} or C{type}.
473 '''
474 if other: # most common, just one arg B{C{other}}
475 other0 = other[0]
476 if isinstance(other0, self.__class__) or \
477 isinstance(self, other0.__class__):
478 return other0
480 other, name, up = _xother3(self, other, **name_other_up)
481 if isinstance(self, other.__class__) or \
482 isinstance(other, self.__class__):
483 return _xnamed(other, name)
485 raise _xotherError(self, other, name=name, up=up + 1)
487 def toRepr(self, **kwds): # PYCHOK expected
488 '''(INTERNAL) I{Could be overloaded}.
490 @kwarg kwds: Optional, C{toStr} keyword arguments.
492 @return: C{toStr}() with keyword arguments (as C{str}).
493 '''
494 t = lrstrip(self.toStr(**kwds))
495# if self.name:
496# t = NN(Fmt.EQUAL(name=repr(self.name)), sep, t)
497 return Fmt.PAREN(self.classname, t) # XXX (self.named, t)
499# def toRepr(self, **kwds)
500# if kwds:
501# s = NN.join(reprs((self,), **kwds))
502# else: # super().__repr__ only for Python 3+
503# s = super(self.__class__, self).__repr__()
504# return Fmt.PAREN(self.named, s) # clips(s)
506 def toStr(self, **kwds): # PYCHOK no cover
507 '''I{Must be overloaded}.'''
508 notOverloaded(self, **kwds)
510# def toStr(self, **kwds):
511# if kwds:
512# s = NN.join(strs((self,), **kwds))
513# else: # super().__str__ only for Python 3+
514# s = super(self.__class__, self).__str__()
515# return s
517 def _update(self, updated, *attrs, **setters):
518 '''(INTERNAL) Zap cached instance attributes and overwrite C{__dict__} or L{Property_RO} values.
519 '''
520 u = _update_all(self, *attrs) if updated else 0
521 if setters:
522 d = self.__dict__
523 # double-check that setters are Property_RO's
524 for n, v in setters.items():
525 if n in d or _hasProperty(self, n, Property_RO):
526 d[n] = v
527 else:
528 raise _AssertionError(n, v, txt=repr(self))
529 u += len(setters)
530 return u
533class _NamedDict(ADict, _Named):
534 '''(INTERNAL) Named C{dict} with key I{and} attribute access
535 to the items.
536 '''
537 def __init__(self, *args, **kwds):
538 if args: # is args[0] a dict?
539 if len(args) != 1: # or not isinstance(args[0], dict)
540 kwds = _name1__(kwds)
541 t = unstr(self.classname, *args, **kwds) # PYCHOK no cover
542 raise _ValueError(args=len(args), txt=t)
543 kwds = _xkwds(dict(args[0]), **kwds) # args[0] overrides kwds
544 n, kwds = _name2__(**kwds)
545 if n:
546 _Named.name.fset(self, n) # see _Named.name
547 ADict.__init__(self, kwds)
549 def __delattr__(self, name):
550 '''Delete an attribute or item by B{C{name}}.
551 '''
552 if name in self: # in ADict.keys(self):
553 ADict.pop(self, name)
554 elif name in (_name_, _name):
555 # ADict.__setattr__(self, name, NN)
556 _Named.rename(self, NN)
557 else:
558 ADict.__delattr__(self, name)
560 def __getattr__(self, name):
561 '''Get the value of an item by B{C{name}}.
562 '''
563 try:
564 return self[name]
565 except KeyError:
566 if name == _name_:
567 return _Named.name.fget(self)
568 raise ADict._AttributeError(self, self._DOT_(name))
570 def __getitem__(self, key):
571 '''Get the value of an item by B{C{key}}.
572 '''
573 if key == _name_:
574 raise self._KeyError(key)
575 return ADict.__getitem__(self, key)
577 def _KeyError(self, key, *value): # PYCHOK no cover
578 '''(INTERNAL) Create a C{KeyError}.
579 '''
580 n = self.name or self.__class__.__name__
581 t = Fmt.SQUARE(n, key)
582 if value:
583 t = Fmt.EQUALSPACED(t, *value)
584 return _KeyError(t)
586 def __setattr__(self, name, value):
587 '''Set attribute or item B{C{name}} to B{C{value}}.
588 '''
589 if name in self: # in ADict.keys(self)
590 ADict.__setitem__(self, name, value) # self[name] = value
591 else:
592 ADict.__setattr__(self, name, value)
594 def __setitem__(self, key, value):
595 '''Set item B{C{key}} to B{C{value}}.
596 '''
597 if key == _name_:
598 raise self._KeyError(key, repr(value))
599 ADict.__setitem__(self, key, value)
602class _NamedEnum(_NamedDict):
603 '''(INTERNAL) Enum-like C{_NamedDict} with attribute access
604 restricted to valid keys.
605 '''
606 _item_Classes = ()
608 def __init__(self, Class, *Classes, **name):
609 '''New C{_NamedEnum}.
611 @arg Class: Initial class or type acceptable as items
612 values (C{type}).
613 @arg Classes: Additional, acceptable classes or C{type}s.
614 '''
615 self._item_Classes = (Class,) + Classes
616 n = _name__(**name) or NN(Class.__name__, _s_) # _dunder_nameof
617 if n and _xvalid(n, underOK=True):
618 _Named.name.fset(self, n) # see _Named.name
620 def __getattr__(self, name):
621 '''Get the value of an attribute or item by B{C{name}}.
622 '''
623 return _NamedDict.__getattr__(self, name)
625 def __repr__(self):
626 '''Default C{repr(self)}.
627 '''
628 return self.toRepr()
630 def __str__(self):
631 '''Default C{str(self)}.
632 '''
633 return self.toStr()
635 def _assert(self, **kwds):
636 '''(INTERNAL) Check attribute name against given, registered name.
637 '''
638 pypy = _isPyPy()
639 _isa = isinstance
640 for n, v in kwds.items():
641 if _isa(v, _LazyNamedEnumItem): # property
642 assert (n == v.name) if pypy else (n is v.name)
643 # assert not hasattr(self.__class__, n)
644 setattr(self.__class__, n, v)
645 elif _isa(v, self._item_Classes): # PYCHOK no cover
646 assert self[n] is v and getattr(self, n) \
647 and self.find(v) == n
648 else:
649 raise _TypeError(v, name=n)
651 def find(self, item, dflt=None, all=False):
652 '''Find a registered item.
654 @arg item: The item to look for (any C{type}).
655 @kwarg dflt: Value to return if not found (any C{type}).
656 @kwarg all: Use C{True} to search I{all} items or C{False} only
657 the currently I{registered} ones (C{bool}).
659 @return: The B{C{item}}'s name if found (C{str}), or C{{dflt}}
660 if there is no such B{C{item}}.
661 '''
662 for k, v in self.items(all=all): # or ADict.items(self)
663 if v is item:
664 return k
665 return dflt
667 def get(self, name, dflt=None):
668 '''Get the value of a I{registered} item.
670 @arg name: The name of the item (C{str}).
671 @kwarg dflt: Value to return (any C{type}).
673 @return: The item with B{C{name}} if found, or B{C{dflt}} if
674 there is no I{registered} item with that B{C{name}}.
675 '''
676 # getattr needed to instantiate L{_LazyNamedEnumItem}
677 return getattr(self, name, dflt)
679 def items(self, all=False, asorted=False):
680 '''Yield all or only the I{registered} items.
682 @kwarg all: Use C{True} to yield I{all} items or C{False} for
683 only the currently I{registered} ones (C{bool}).
684 @kwarg asorted: If C{True}, yield the items in I{alphabetical,
685 case-insensitive} order (C{bool}).
686 '''
687 if all: # instantiate any remaining L{_LazyNamedEnumItem}
688 _isa = isinstance
689 for n, p in tuple(self.__class__.__dict__.items()):
690 if _isa(p, _LazyNamedEnumItem):
691 _ = getattr(self, n)
692 return itemsorted(self) if asorted else ADict.items(self)
694 def keys(self, **all_asorted):
695 '''Yield the name (C{str}) of I{all} or only the currently I{registered}
696 items, optionally sorted I{alphabetically, case-insensitively}.
698 @kwarg all_asorted: See method C{items}.
699 '''
700 for k, _ in self.items(**all_asorted):
701 yield k
703 def popitem(self):
704 '''Remove I{an, any} currently I{registed} item.
706 @return: The removed item.
707 '''
708 return self._zapitem(*ADict.popitem(self))
710 def register(self, item):
711 '''Registed one new item or I{all} or I{any} unregistered ones.
713 @arg item: The item (any C{type}) or B{I{all}} or B{C{any}}.
715 @return: The item name (C{str}) or C("all") or C{"any"}.
717 @raise NameError: An B{C{item}} with that name is already
718 registered the B{C{item}} has no or an
719 invalid name.
721 @raise TypeError: The B{C{item}} type invalid.
722 '''
723 if item is all or item is any:
724 _ = self.items(all=True)
725 n = item.__name__
726 else:
727 try:
728 n = item.name
729 if not (n and isstr(n) and isidentifier(n)):
730 raise ValueError()
731 except (AttributeError, ValueError, TypeError) as x:
732 n = _DOT_(_item_, _name_)
733 raise _NameError(n, item, cause=x)
734 if n in self:
735 t = _SPACE_(_item_, self._DOT_(n), _exists_)
736 raise _NameError(t, txt=repr(item))
737 if not isinstance(item, self._item_Classes): # _xinstanceof
738 n = self._DOT_(n)
739 raise _TypesError(n, item, *self._item_Classes)
740 self[n] = item
741 return n
743 def unregister(self, name_or_item):
744 '''Remove a I{registered} item.
746 @arg name_or_item: Name (C{str}) or the item (any C{type}).
748 @return: The unregistered item.
750 @raise AttributeError: No such B{C{item}}.
752 @raise NameError: No item with that B{C{name}}.
753 '''
754 if isstr(name_or_item):
755 name = name_or_item
756 else:
757 name = self.find(name_or_item, dflt=MISSING) # all=True?
758 if name is MISSING:
759 t = _SPACE_(_no_, _such_, self.classname, _item_)
760 raise _AttributeError(t, txt=repr(name_or_item))
761 try:
762 item = ADict.pop(self, name)
763 except KeyError:
764 raise _NameError(item=self._DOT_(name), txt=_doesn_t_exist_)
765 return self._zapitem(name, item)
767 pop = unregister
769 def toRepr(self, prec=6, fmt=Fmt.F, sep=_COMMANL_, **all_asorted): # PYCHOK _NamedDict, ADict
770 '''Like C{repr(dict)} but C{name}s optionally sorted and
771 C{floats} formatted by function L{pygeodesy.fstr}.
772 '''
773 t = ((self._DOT_(n), v) for n, v in self.items(**all_asorted))
774 return sep.join(pairs(t, prec=prec, fmt=fmt, sep=_COLONSPACE_))
776 def toStr(self, *unused, **all_asorted): # PYCHOK _NamedDict, ADict
777 '''Return a string with all C{name}s, optionally sorted.
778 '''
779 return self._DOT_(_COMMASPACEDOT_.join(self.keys(**all_asorted)))
781 def values(self, **all_asorted):
782 '''Yield the value (C{type}) of all or only the I{registered} items,
783 optionally sorted I{alphabetically} and I{case-insensitively}.
785 @kwarg all_asorted: See method C{items}.
786 '''
787 for _, v in self.items(**all_asorted):
788 yield v
790 def _zapitem(self, name, item):
791 # remove _LazyNamedEnumItem property value if still present
792 if self.__dict__.get(name, None) is item:
793 self.__dict__.pop(name) # [name] = None
794 item._enum = None
795 return item
798class _LazyNamedEnumItem(property_RO): # XXX or descriptor?
799 '''(INTERNAL) Lazily instantiated L{_NamedEnumItem}.
800 '''
801 pass
804def _lazyNamedEnumItem(name, *args, **kwds):
805 '''(INTERNAL) L{_LazyNamedEnumItem} property-like factory.
807 @see: Luciano Ramalho, "Fluent Python", O'Reilly, Example
808 19-24, 2016 p. 636 or Example 22-28, 2022 p. 869+
809 '''
810 def _fget(inst):
811 # assert isinstance(inst, _NamedEnum)
812 try: # get the item from the instance' __dict__
813 # item = inst.__dict__[name] # ... or ADict
814 item = inst[name]
815 except KeyError:
816 # instantiate an _NamedEnumItem, it self-registers
817 item = inst._Lazy(*args, **_xkwds(kwds, name=name))
818 # assert inst[name] is item # MUST be registered
819 # store the item in the instance' __dict__ ...
820 # inst.__dict__[name] = item # ... or update the
821 inst.update({name: item}) # ... ADict for Triaxials
822 # remove the property from the registry class, such that
823 # (a) the property no longer overrides the instance' item
824 # in inst.__dict__ and (b) _NamedEnum.items(all=True) only
825 # sees any un-instantiated ones yet to be instantiated
826 p = getattr(inst.__class__, name, None)
827 if isinstance(p, _LazyNamedEnumItem):
828 delattr(inst.__class__, name)
829 # assert isinstance(item, _NamedEnumItem)
830 return item
832 p = _LazyNamedEnumItem(_fget)
833 p.name = name
834 return p
837class _NamedEnumItem(_NamedBase):
838 '''(INTERNAL) Base class for items in a C{_NamedEnum} registery.
839 '''
840 _enum = None
842# def __ne__(self, other): # XXX fails for Lcc.conic = conic!
843# '''Compare this and an other item.
844#
845# @return: C{True} if different, C{False} otherwise.
846# '''
847# return not self.__eq__(other)
849 @property_doc_(''' the I{registered} name (C{str}).''')
850 def name(self):
851 '''Get the I{registered} name (C{str}).
852 '''
853 return self._name
855 @name.setter # PYCHOK setter!
856 def name(self, name):
857 '''Set the name, unless already registered (C{str}).
858 '''
859 name = _name__(name) or _NN_
860 if self._enum:
861 raise _NameError(name, self, txt=_registered_) # _TypeError
862 if name:
863 self._name = 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 name = _name__(name)
872 if name and _xvalid(name, underOK=True):
873 self.name = name
874 if name[:1].isalpha(): # '_...' not registered
875 enum.register(self)
876 self._enum = enum
878 def unregister(self):
879 '''Remove this instance from its C{_NamedEnum} registry.
881 @raise AssertionError: Mismatch of this and registered item.
883 @raise NameError: This item is unregistered.
884 '''
885 enum = self._enum
886 if enum and self.name and self.name in enum:
887 item = enum.unregister(self.name)
888 if item is not self: # PYCHOK no cover
889 t = _SPACE_(repr(item), _vs_, repr(self))
890 raise _AssertionError(t)
893class _NamedTuple(tuple, _Named):
894 '''(INTERNAL) Base for named C{tuple}s with both index I{and}
895 attribute name access to the items.
897 @note: This class is similar to Python's C{namedtuple},
898 but statically defined, lighter and limited.
899 '''
900 _Names_ = () # item names, non-identifier, no leading underscore
901 '''Tuple specifying the C{name} of each C{Named-Tuple} item.
903 @note: Specify at least 2 item names.
904 '''
905 _Units_ = () # .units classes
906 '''Tuple defining the C{units} of the value of each C{Named-Tuple} item.
908 @note: The C{len(_Units_)} must match C{len(_Names_)}.
909 '''
910 _validated = False # set to True I{per sub-class!}
912 def __new__(cls, arg, *args, **iteration_name):
913 '''New L{_NamedTuple} initialized with B{C{positional}} arguments.
915 @arg arg: Tuple items (C{tuple}, C{list}, ...) or first tuple
916 item of several more in other positional arguments.
917 @arg args: Tuple items (C{any}), all positional arguments.
918 @kwarg iteration_name: Only keyword arguments C{B{iteration}=None}
919 and C{B{name}=NN} are used, any other are
920 I{silently} ignored.
922 @raise LenError: Unequal number of positional arguments and
923 number of item C{_Names_} or C{_Units_}.
925 @raise TypeError: The C{_Names_} or C{_Units_} attribute is
926 not a C{tuple} of at least 2 items.
928 @raise ValueError: Item name is not a C{str} or valid C{identifier}
929 or starts with C{underscore}.
930 '''
931 n, args = len2(((arg,) + args) if args else arg)
932 self = tuple.__new__(cls, args)
933 if not self._validated:
934 self._validate()
936 N = len(self._Names_)
937 if n != N:
938 raise LenError(self.__class__, args=n, _Names_=N)
940 if iteration_name:
941 i, name = _xkwds_pop2(iteration_name, iteration=None)
942 if i is not None:
943 self._iteration = i
944 if name:
945 self.name = name
946 return self
948 def __delattr__(self, name):
949 '''Delete an attribute by B{C{name}}.
951 @note: Items can not be deleted.
952 '''
953 if name in self._Names_:
954 t = _SPACE_(_del_, self._DOT_(name))
955 raise _TypeError(t, txt=_immutable_)
956 elif name in (_name_, _name):
957 _Named.__setattr__(self, name, NN) # XXX _Named.name.fset(self, NN)
958 else:
959 tuple.__delattr__(self, name)
961 def __getattr__(self, name):
962 '''Get the value of an attribute or item by B{C{name}}.
963 '''
964 try:
965 return tuple.__getitem__(self, self._Names_.index(name))
966 except IndexError as x:
967 raise _IndexError(self._DOT_(name), cause=x)
968 except ValueError: # e.g. _iteration
969 return tuple.__getattr__(self, name) # __getattribute__
971# def __getitem__(self, index): # index, slice, etc.
972# '''Get the item(s) at an B{C{index}} or slice.
973# '''
974# return tuple.__getitem__(self, index)
976 def __hash__(self):
977 return tuple.__hash__(self)
979 def __repr__(self):
980 '''Default C{repr(self)}.
981 '''
982 return self.toRepr()
984 def __setattr__(self, name, value):
985 '''Set attribute or item B{C{name}} to B{C{value}}.
986 '''
987 if name in self._Names_:
988 t = Fmt.EQUALSPACED(self._DOT_(name), repr(value))
989 raise _TypeError(t, txt=_immutable_)
990 elif name in (_name_, _name):
991 _Named.__setattr__(self, name, value) # XXX _Named.name.fset(self, value)
992 else: # e.g. _iteration
993 tuple.__setattr__(self, name, value)
995 def __str__(self):
996 '''Default C{repr(self)}.
997 '''
998 return self.toStr()
1000 def _DOT_(self, *names):
1001 '''(INTERNAL) Period-join C{self.classname} and C{names}.
1002 '''
1003 return _DOT_(self.classname, *names)
1005 def dup(self, name=NN, **items):
1006 '''Duplicate this tuple replacing one or more items.
1008 @kwarg name: Optional new name (C{str}).
1009 @kwarg items: Items to be replaced (C{name=value} pairs), if any.
1011 @return: A copy of this tuple with B{C{items}}.
1013 @raise NameError: Some B{C{items}} invalid.
1014 '''
1015 t = list(self)
1016 U = self._Units_
1017 if items:
1018 _ix = self._Names_.index
1019 _2U = _MODS.units._toUnit
1020 try:
1021 for n, v in items.items():
1022 i = _ix(n)
1023 t[i] = _2U(U[i], v, name=n)
1024 except ValueError: # bad item name
1025 raise _NameError(self._DOT_(n), v, this=self)
1026 return self.classof(*t).reUnit(*U, name=name)
1028 def items(self):
1029 '''Yield the items, each as a C{(name, value)} pair (C{2-tuple}).
1031 @see: Method C{.units}.
1032 '''
1033 for n, v in _zip(self._Names_, self): # strict=True
1034 yield n, v
1036 iteritems = items
1038 def reUnit(self, *Units, **name):
1039 '''Replace some of this C{Named-Tuple}'s C{Units}.
1041 @arg Units: One or more C{Unit} classes, all positional.
1042 @kwarg name: Optional C{B{name}=NN} (C{str}).
1044 @return: This instance with updated C{Units}.
1046 @note: This C{Named-Tuple}'s values are I{not updated}.
1047 '''
1048 U = self._Units_
1049 n = min(len(U), len(Units))
1050 if n:
1051 R = Units + U[n:]
1052 if R != U:
1053 self._Units_ = R
1054 return self.renamed(name) if name else self
1056 def toRepr(self, prec=6, sep=_COMMASPACE_, fmt=Fmt.F, **unused): # PYCHOK signature
1057 '''Return this C{Named-Tuple} items as C{name=value} string(s).
1059 @kwarg prec: The C{float} precision, number of decimal digits (0..9).
1060 Trailing zero decimals are stripped for B{C{prec}} values
1061 of 1 and above, but kept for negative B{C{prec}} values.
1062 @kwarg sep: Separator to join (C{str}).
1063 @kwarg fmt: Optional C{float} format (C{letter}).
1065 @return: Tuple items (C{str}).
1066 '''
1067 t = pairs(self.items(), prec=prec, fmt=fmt)
1068# if self.name:
1069# t = (Fmt.EQUAL(name=repr(self.name)),) + t
1070 return Fmt.PAREN(self.named, sep.join(t)) # XXX (self.classname, sep.join(t))
1072 def toStr(self, prec=6, sep=_COMMASPACE_, fmt=Fmt.F, **unused): # PYCHOK signature
1073 '''Return this C{Named-Tuple} items as string(s).
1075 @kwarg prec: The C{float} precision, number of decimal digits (0..9).
1076 Trailing zero decimals are stripped for B{C{prec}} values
1077 of 1 and above, but kept for negative B{C{prec}} values.
1078 @kwarg sep: Separator to join (C{str}).
1079 @kwarg fmt: Optional C{float} format (C{letter}).
1081 @return: Tuple items (C{str}).
1082 '''
1083 return Fmt.PAREN(sep.join(reprs(self, prec=prec, fmt=fmt)))
1085 def toUnits(self, Error=UnitError, **name): # overloaded in .frechet, .hausdorff
1086 '''Return a copy of this C{Named-Tuple} with each item value wrapped
1087 as an instance of its L{units} class.
1089 @kwarg Error: Error to raise for L{units} issues (C{UnitError}).
1090 @kwarg name: Optional C{B{name}=NN} (C{str}).
1092 @return: A duplicate of this C{Named-Tuple} (C{C{Named-Tuple}}).
1094 @raise Error: Invalid C{Named-Tuple} item or L{units} class.
1095 '''
1096 t = tuple(v for _, v in self.units(Error=Error))
1097 return self.classof(*t).reUnit(*self._Units_, **name)
1099 def units(self, **Error):
1100 '''Yield the items, each as a C{2-tuple (name, value}) with the
1101 value wrapped as an instance of its L{units} class.
1103 @kwarg Error: Optional C{B{Error}=UnitError} to raise.
1105 @raise Error: Invalid C{Named-Tuple} item or L{units} class.
1107 @see: Method C{.items}.
1108 '''
1109 _2U = _MODS.units._toUnit
1110 for n, v, U in _zip(self._Names_, self, self._Units_): # strict=True
1111 yield n, _2U(U, v, name=n, **Error)
1113 iterunits = units
1115 def _validate(self, underOK=False): # see .EcefMatrix
1116 '''(INTERNAL) One-time check of C{_Names_} and C{_Units_}
1117 for each C{_NamedUnit} I{sub-class separately}.
1118 '''
1119 ns = self._Names_
1120 if not (isinstance(ns, tuple) and len(ns) > 1): # XXX > 0
1121 raise _TypeError(self._DOT_(_Names_), ns)
1122 for i, n in enumerate(ns):
1123 if not _xvalid(n, underOK=underOK):
1124 t = Fmt.SQUARE(_Names_=i) # PYCHOK no cover
1125 raise _ValueError(self._DOT_(t), n)
1127 us = self._Units_
1128 if not isinstance(us, tuple):
1129 raise _TypeError(self._DOT_(_Units_), us)
1130 if len(us) != len(ns):
1131 raise LenError(self.__class__, _Units_=len(us), _Names_=len(ns))
1132 for i, u in enumerate(us):
1133 if not (u is None or callable(u)):
1134 t = Fmt.SQUARE(_Units_=i) # PYCHOK no cover
1135 raise _TypeError(self._DOT_(t), u)
1137 self.__class__._validated = True
1139 def _xtend(self, xTuple, *items, **name):
1140 '''(INTERNAL) Extend this C{Named-Tuple} with C{items} to an other B{C{xTuple}}.
1141 '''
1142 _xsubclassof(_NamedTuple, xTuple=xTuple)
1143 if len(xTuple._Names_) != (len(self._Names_) + len(items)) or \
1144 xTuple._Names_[:len(self)] != self._Names_: # PYCHOK no cover
1145 c = NN(self.classname, repr(self._Names_))
1146 x = NN(xTuple.__name__, repr(xTuple._Names_))
1147 raise TypeError(_SPACE_(c, _vs_, x))
1148 t = self + items
1149 return xTuple(t, name=self._name__(name)) # .reUnit(*self._Units_)
1152def callername(up=1, dflt=NN, source=False, underOK=False):
1153 '''Get the name of the invoking callable.
1155 @kwarg up: Number of call stack frames up (C{int}).
1156 @kwarg dflt: Default return value (C{any}).
1157 @kwarg source: Include source file name and line number (C{bool}).
1158 @kwarg underOK: If C{True}, private, internal callables are OK,
1159 otherwise private callables are skipped (C{bool}).
1161 @return: The callable name (C{str}) or B{C{dflt}} if none found.
1162 '''
1163 try: # see .lazily._caller3
1164 for u in range(up, up + 32):
1165 n, f, s = _caller3(u)
1166 if n and (underOK or n.startswith(_DUNDER_) or
1167 not n.startswith(_UNDER_)):
1168 if source:
1169 n = NN(n, _AT_, f, _COLON_, str(s))
1170 return n
1171 except (AttributeError, ValueError):
1172 pass
1173 return dflt
1176def _callername2(args, callername=NN, source=False, underOK=False, up=_UP, **kwds):
1177 '''(INTERNAL) Extract C{callername}, C{source}, C{underOK} and C{up} from C{kwds}.
1178 '''
1179 n = callername or _MODS.named.callername(up=up + 1, source=source,
1180 underOK=underOK or bool(args or kwds))
1181 return n, kwds
1184def _callname(name, class_name, self_name, up=1):
1185 '''(INTERNAL) Assemble the name for an invokation.
1186 '''
1187 n, c = class_name, callername(up=up + 1)
1188 if c:
1189 n = _DOT_(n, Fmt.PAREN(c, name))
1190 if self_name:
1191 n = _SPACE_(n, repr(self_name))
1192 return n
1195def classname(inst, prefixed=None):
1196 '''Return the instance' class name optionally prefixed with the
1197 module name.
1199 @arg inst: The object (any C{type}).
1200 @kwarg prefixed: Include the module name (C{bool}), see
1201 function C{classnaming}.
1203 @return: The B{C{inst}}'s C{[module.]class} name (C{str}).
1204 '''
1205 if prefixed is None:
1206 prefixed = getattr(inst, classnaming.__name__, prefixed)
1207 return modulename(inst.__class__, prefixed=prefixed)
1210def classnaming(prefixed=None):
1211 '''Get/set the default class naming for C{[module.]class} names.
1213 @kwarg prefixed: Include the module name (C{bool}).
1215 @return: Previous class naming setting (C{bool}).
1216 '''
1217 t = _Named._classnaming
1218 if prefixed in (True, False):
1219 _Named._classnaming = prefixed
1220 return t
1223def modulename(clas, prefixed=None): # in .basics._xversion
1224 '''Return the class name optionally prefixed with the
1225 module name.
1227 @arg clas: The class (any C{class}).
1228 @kwarg prefixed: Include the module name (C{bool}), see
1229 function C{classnaming}.
1231 @return: The B{C{class}}'s C{[module.]class} name (C{str}).
1232 '''
1233 try:
1234 n = clas.__name__
1235 except AttributeError:
1236 n = clas if isstr(clas) else _dunder_name_
1237 if prefixed or (classnaming() if prefixed is None else False):
1238 try:
1239 m = clas.__module__.rsplit(_DOT_, 1)
1240 n = _DOT_.join(m[1:] + [n])
1241 except AttributeError:
1242 pass
1243 return n
1246# def _name__(name=NN, name__=None, _or_nameof=None, **kwds):
1247# '''(INTERNAL) Get single keyword argument C{B{name}=NN|None}.
1248# '''
1249# if kwds: # "unexpected keyword arguments ..."
1250# m = _MODS.errors
1251# raise m._UnexpectedError(**kwds)
1252# if name: # is given
1253# n = _name__(**name) if isinstance(name, dict) else str(name)
1254# elif name__ is not None:
1255# n = getattr(name__, _dunder_name_, NN) # _xattr(name__, __name__=NN)
1256# else:
1257# n = name # NN or None or {} or any False type
1258# if _or_nameof is not None and not n:
1259# n = getattr(_or_nameof, _name_, NN) # _xattr(_or_nameof, name=NN)
1260# return n # str or None or {}
1263def _name__(name=NN, **kwds):
1264 '''(INTERNAL) Get single keyword argument C{B{name}=NN|None}.
1265 '''
1266 if name or kwds:
1267 name, kwds = _name2__(name, **kwds)
1268 if kwds: # "unexpected keyword arguments ..."
1269 raise _UnexpectedError(**kwds)
1270 return name if name or name is None else NN
1273def _name1__(kwds_name, **name__or_nameof):
1274 '''(INTERNAL) Resolve and set the C{B{name}=NN}.
1275 '''
1276 if kwds_name or name__or_nameof:
1277 n, kwds_name = _name2__(kwds_name, **name__or_nameof)
1278 kwds_name.update(name=n)
1279 return kwds_name
1282def _name2__(name=NN, name__=None, _or_nameof=None, **kwds):
1283 '''(INTERNAL) Get the C{B{name}=NN|None} and other C{kwds}.
1284 '''
1285 if name: # is given
1286 if isinstance(name, dict):
1287 kwds.update(name) # kwds = _xkwds(kwds, **name)?
1288 n, kwds = _name2__(**kwds)
1289 else:
1290 n = str(name)
1291 elif name__ is not None:
1292 n = _dunder_nameof(name__, NN)
1293 else:
1294 n = name if name is None else NN
1295 if _or_nameof is not None and not n:
1296 n = _xattr(_or_nameof, name=NN) # nameof
1297 return n, kwds # (str or None or {}), dict
1300def nameof(inst):
1301 '''Get the name of an instance.
1303 @arg inst: The object (any C{type}).
1305 @return: The instance' name (C{str}) or C{""}.
1306 '''
1307 n = _xattr(inst, name=NN)
1308 if not n: # and isinstance(inst, property):
1309 try:
1310 n = inst.fget.__name__
1311 except AttributeError:
1312 n = NN
1313 return n
1316def _notDecap(where):
1317 '''De-Capitalize C{where.__name__}.
1318 '''
1319 n = where.__name__
1320 c = n[3].lower() # len(_not_)
1321 return NN(n[:3], _SPACE_, c, n[4:])
1324def _notError(inst, name, args, kwds): # PYCHOK no cover
1325 '''(INTERNAL) Format an error message.
1326 '''
1327 n = _DOT_(classname(inst, prefixed=True), _dunder_nameof(name, name))
1328 m = _COMMASPACE_.join(modulename(c, prefixed=True) for c in inst.__class__.__mro__[1:-1])
1329 return _COMMASPACE_(unstr(n, *args, **kwds), Fmt.PAREN(_MRO_, m))
1332def _NotImplemented(inst, *other, **kwds):
1333 '''(INTERNAL) Raise a C{__special__} error or return C{NotImplemented},
1334 but only if env variable C{PYGEODESY_NOTIMPLEMENTED=std}.
1335 '''
1336 if _std_NotImplemented:
1337 return NotImplemented
1338 n, kwds = _callername2(other, **kwds) # source=True
1339 t = unstr(_DOT_(classname(inst), n), *other, **kwds)
1340 raise _NotImplementedError(t, txt=repr(inst))
1343def notImplemented(inst, *args, **kwds): # PYCHOK no cover
1344 '''Raise a C{NotImplementedError} for a missing instance method or
1345 property or for a missing caller feature.
1347 @arg inst: Caller instance (C{any}) or C{None} for function.
1348 @arg args: Method or property positional arguments (any C{type}s).
1349 @arg kwds: Method or property keyword arguments (any C{type}s),
1350 except C{B{callername}=NN}, C{B{underOK}=False} and
1351 C{B{up}=2}.
1352 '''
1353 n, kwds = _callername2(args, **kwds)
1354 t = _notError(inst, n, args, kwds) if inst else unstr(n, *args, **kwds)
1355 raise _NotImplementedError(t, txt=_notDecap(notImplemented))
1358def notOverloaded(inst, *args, **kwds): # PYCHOK no cover
1359 '''Raise an C{AssertionError} for a method or property not overloaded.
1361 @arg inst: Instance (C{any}).
1362 @arg args: Method or property positional arguments (any C{type}s).
1363 @arg kwds: Method or property keyword arguments (any C{type}s),
1364 except C{B{callername}=NN}, C{B{underOK}=False} and
1365 C{B{up}=2}.
1366 '''
1367 n, kwds = _callername2(args, **kwds)
1368 t = _notError(inst, n, args, kwds)
1369 raise _AssertionError(t, txt=_notDecap(notOverloaded))
1372def _Pass(arg, **unused): # PYCHOK no cover
1373 '''(INTERNAL) I{Pass-thru} class for C{_NamedTuple._Units_}.
1374 '''
1375 return arg
1378def _xjoined_(prefix, name=NN, enquote=True, **name__or_nameof):
1379 '''(INTERNAL) Join C{prefix} and non-empty C{name}.
1380 '''
1381 if name__or_nameof:
1382 name = _name__(name, **name__or_nameof)
1383 if name and prefix:
1384 if enquote:
1385 name = repr(name)
1386 t = _SPACE_(prefix, name)
1387 else:
1388 t = prefix or name
1389 return t
1392def _xnamed(inst, name=NN, force=False, **name__or_nameof):
1393 '''(INTERNAL) Set the instance' C{.name = B{name}}.
1395 @arg inst: The instance (C{_Named}).
1396 @kwarg name: The name (C{str}).
1397 @kwarg force: If C{True}, force rename (C{bool}).
1399 @return: The B{C{inst}}, renamed if B{C{force}}d
1400 or if not named before.
1401 '''
1402 if name__or_nameof:
1403 name = _name__(name, **name__or_nameof)
1404 if name and isinstance(inst, _Named):
1405 if not inst.name:
1406 inst.name = name
1407 elif force:
1408 inst.rename(name)
1409 return inst
1412def _xother3(inst, other, name=_other_, up=1, **name_other):
1413 '''(INTERNAL) Get C{name} and C{up} for a named C{other}.
1414 '''
1415 if name_other: # and other is None
1416 name, other = _xkwds_item2(name_other)
1417 elif other and len(other) == 1:
1418 name, other = _name__(name), other[0]
1419 else:
1420 raise _AssertionError(name, other, txt=classname(inst, prefixed=True))
1421 return other, name, up
1424def _xotherError(inst, other, name=_other_, up=1):
1425 '''(INTERNAL) Return a C{_TypeError} for an incompatible, named C{other}.
1426 '''
1427 n = _callname(name, classname(inst, prefixed=True), inst.name, up=up + 1)
1428 return _TypeError(name, other, txt=_incompatible(n))
1431def _xvalid(name, underOK=False):
1432 '''(INTERNAL) Check valid attribute name C{name}.
1433 '''
1434 return bool(name and isstr(name)
1435 and name != _name_
1436 and (underOK or not name.startswith(_UNDER_))
1437 and (not iskeyword(name))
1438 and isidentifier(name))
1441__all__ += _ALL_DOCS(_Named,
1442 _NamedBase, # _NamedDict,
1443 _NamedEnum, _NamedEnumItem,
1444 _NamedTuple)
1446# **) MIT License
1447#
1448# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
1449#
1450# Permission is hereby granted, free of charge, to any person obtaining a
1451# copy of this software and associated documentation files (the "Software"),
1452# to deal in the Software without restriction, including without limitation
1453# the rights to use, copy, modify, merge, publish, distribute, sublicense,
1454# and/or sell copies of the Software, and to permit persons to whom the
1455# Software is furnished to do so, subject to the following conditions:
1456#
1457# The above copyright notice and this permission notice shall be included
1458# in all copies or substantial portions of the Software.
1459#
1460# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1461# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1462# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1463# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
1464# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
1465# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
1466# OTHER DEALINGS IN THE SOFTWARE.