Coverage for pygeodesy/named.py: 97%

461 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-05-02 14:35 -0400

1 

2# -*- coding: utf-8 -*- 

3 

4u'''(INTERNAL) Nameable class instances. 

5 

6Classes C{_Named}, C{_NamedDict}, C{_NamedEnum}, C{_NamedEnumItem} and 

7C{_NamedTuple} and several subclasses thereof, all with nameable instances. 

8 

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. 

12 

13@see: Module L{pygeodesy.namedTuples} for (most of) the C{Named-Tuples}. 

14''' 

15 

16from pygeodesy.basics import isclass, isidentifier, iskeyword, isstr, issubclassof, \ 

17 itemsorted, len2, _sizeof, _xcopy, _xdup, _zip 

18from pygeodesy.errors import _AssertionError, _AttributeError, _incompatible, \ 

19 _IndexError, _IsnotError, _KeyError, LenError, \ 

20 _NameError, _NotImplementedError, _TypeError, \ 

21 _TypesError, UnitError, _ValueError, _xattr, _xkwds, \ 

22 _xkwds_get, _xkwds_item2, _xkwds_pop2 

23from pygeodesy.interns import MISSING, NN, _at_, _AT_, _COLON_, _COLONSPACE_, _COMMA_, \ 

24 _COMMASPACE_, _doesn_t_exist_, _DOT_, _DUNDER_, _EQUAL_, \ 

25 _exists_, _immutable_, _name_, _NL_, _NN_, _no_, _other_, \ 

26 _s_, _SPACE_, _std_, _UNDER_, _valid_, _vs_, \ 

27 _dunder_nameof, _isPyPy, _under 

28from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS, _caller3, _getenv 

29from pygeodesy.props import _allPropertiesOf_n, deprecated_method, _hasProperty, \ 

30 _update_all, property_doc_, Property_RO, property_RO, \ 

31 _update_attrs 

32from pygeodesy.streprs import attrs, Fmt, lrstrip, pairs, reprs, unstr 

33 

34__all__ = _ALL_LAZY.named 

35__version__ = '24.04.07' 

36 

37_COMMANL_ = _COMMA_ + _NL_ 

38_COMMASPACEDOT_ = _COMMASPACE_ + _DOT_ 

39_del_ = 'del' 

40_item_ = 'item' 

41_MRO_ = 'MRO' 

42# __DUNDER gets mangled in class 

43_name = _under(_name_) 

44_Names_ = '_Names_' 

45_registered_ = 'registered' # PYCHOK used! 

46_std_NotImplemented = _getenv('PYGEODESY_NOTIMPLEMENTED', NN).lower() == _std_ 

47_Units_ = '_Units_' 

48_UP = 2 

49 

50 

51def _xjoined_(prefix, name): 

52 '''(INTERNAL) Join C{pref} and non-empty C{name}. 

53 ''' 

54 return _SPACE_(prefix, repr(name)) if name and prefix else (prefix or name) 

55 

56 

57def _xnamed(inst, name, force=False): 

58 '''(INTERNAL) Set the instance' C{.name = B{name}}. 

59 

60 @arg inst: The instance (C{_Named}). 

61 @arg name: The name (C{str}). 

62 @kwarg force: Force name change (C{bool}). 

63 

64 @return: The B{C{inst}}, named if B{C{force}}d or 

65 not named before. 

66 ''' 

67 if name and isinstance(inst, _Named): 

68 if not inst.name: 

69 inst.name = name 

70 elif force: 

71 inst.rename(name) 

72 return inst 

73 

74 

75def _xother3(inst, other, name=_other_, up=1, **name_other): 

76 '''(INTERNAL) Get C{name} and C{up} for a named C{other}. 

77 ''' 

78 if name_other: # and other is None 

79 name, other = _xkwds_item2(name_other) 

80 elif other and len(other) == 1: 

81 other = other[0] 

82 else: 

83 raise _AssertionError(name, other, txt=classname(inst, prefixed=True)) 

84 return other, name, up 

85 

86 

87def _xotherError(inst, other, name=_other_, up=1): 

88 '''(INTERNAL) Return a C{_TypeError} for an incompatible, named C{other}. 

89 ''' 

90 n = _callname(name, classname(inst, prefixed=True), inst.name, up=up + 1) 

91 return _TypeError(name, other, txt=_incompatible(n)) 

92 

93 

94def _xvalid(name, underOK=False): 

95 '''(INTERNAL) Check valid attribute name C{name}. 

96 ''' 

97 return bool(name and isstr(name) 

98 and name != _name_ 

99 and (underOK or not name.startswith(_UNDER_)) 

100 and (not iskeyword(name)) 

101 and isidentifier(name)) 

102 

103 

104class ADict(dict): 

105 '''A C{dict} with both key I{and} attribute access to 

106 the C{dict} items. 

107 ''' 

108 _iteration = None # Iteration number (C{int}) or C{None} 

109 

110 def __getattr__(self, name): 

111 '''Get the value of an item by B{C{name}}. 

112 ''' 

113 try: 

114 return self[name] 

115 except KeyError: 

116 if name == _name_: 

117 return NN 

118 raise self._AttributeError(name) 

119 

120 def __repr__(self): 

121 '''Default C{repr(self)}. 

122 ''' 

123 return self.toRepr() 

124 

125 def __str__(self): 

126 '''Default C{str(self)}. 

127 ''' 

128 return self.toStr() 

129 

130 def _AttributeError(self, name): 

131 '''(INTERNAL) Create an C{AttributeError}. 

132 ''' 

133 if _DOT_ not in name: # NOT classname(self)! 

134 name = _DOT_(self.__class__.__name__, name) 

135 return _AttributeError(item=name, txt=_doesn_t_exist_) 

136 

137 @property_RO 

138 def iteration(self): # see .named._NamedBase 

139 '''Get the iteration number (C{int}) or 

140 C{None} if not available/applicable. 

141 ''' 

142 return self._iteration 

143 

144 def set_(self, iteration=None, **items): # PYCHOK signature 

145 '''Add one or several new items or replace existing ones. 

146 

147 @kwarg iteration: Optional C{iteration} (C{int}). 

148 @kwarg items: One or more C{name=value} pairs. 

149 ''' 

150 if iteration is not None: 

151 self._iteration = iteration 

152 if items: 

153 dict.update(self, items) 

154 return self # in RhumbLineBase.Intersecant2, _PseudoRhumbLine.Position 

155 

156 def toRepr(self, **prec_fmt): 

157 '''Like C{repr(dict)} but with C{name} prefix and with 

158 C{floats} formatted by function L{pygeodesy.fstr}. 

159 ''' 

160 n = _xattr(self, name=NN) or self.__class__.__name__ 

161 return Fmt.PAREN(n, self._toT(_EQUAL_, **prec_fmt)) 

162 

163 def toStr(self, **prec_fmt): 

164 '''Like C{str(dict)} but with C{floats} formatted by 

165 function L{pygeodesy.fstr}. 

166 ''' 

167 return Fmt.CURLY(self._toT(_COLONSPACE_, **prec_fmt)) 

168 

169 def _toT(self, sep, **kwds): 

170 '''(INTERNAL) Helper for C{.toRepr} and C{.toStr}. 

171 ''' 

172 kwds = _xkwds(kwds, prec=6, fmt=Fmt.F, sep=sep) 

173 return _COMMASPACE_.join(pairs(itemsorted(self), **kwds)) 

174 

175 

176class _Named(object): 

177 '''(INTERNAL) Root class for named objects. 

178 ''' 

179 _iteration = None # iteration number (C{int}) or C{None} 

180 _name = NN # name (C{str}) 

181 _classnaming = False # prefixed (C{bool}) 

182# _updates = 0 # OBSOLETE Property/property updates 

183 

184 def __imatmul__(self, other): # PYCHOK no cover 

185 '''Not implemented.''' 

186 return _NotImplemented(self, other) # PYCHOK Python 3.5+ 

187 

188 def __matmul__(self, other): # PYCHOK no cover 

189 '''Not implemented.''' 

190 return _NotImplemented(self, other) # PYCHOK Python 3.5+ 

191 

192 def __repr__(self): 

193 '''Default C{repr(self)}. 

194 ''' 

195 return Fmt.ANGLE(_SPACE_(self, _at_, hex(id(self)))) 

196 

197 def __rmatmul__(self, other): # PYCHOK no cover 

198 '''Not implemented.''' 

199 return _NotImplemented(self, other) # PYCHOK Python 3.5+ 

200 

201 def __str__(self): 

202 '''Default C{str(self)}. 

203 ''' 

204 return self.named2 

205 

206 def attrs(self, *names, **sep_Nones_pairs_kwds): 

207 '''Join named attributes as I{name=value} strings, with C{float}s formatted by 

208 function L{pygeodesy.fstr}. 

209 

210 @arg names: The attribute names, all positional (C{str}). 

211 @kwarg sep_Nones_pairs_kwds: Keyword arguments for function L{pygeodesy.pairs}, 

212 except C{B{sep}=", "} and C{B{Nones}=True} to in-/exclude missing 

213 or C{None}-valued attributes. 

214 

215 @return: All C{name=value} pairs, joined by B{C{sep}} (C{str}). 

216 

217 @see: Functions L{pygeodesy.attrs}, L{pygeodesy.pairs} and L{pygeodesy.fstr} 

218 ''' 

219 sep, kwds = _xkwds_pop2(sep_Nones_pairs_kwds, sep=_COMMASPACE_) 

220 return sep.join(attrs(self, *names, **kwds)) 

221 

222 @Property_RO 

223 def classname(self): 

224 '''Get this object's C{[module.]class} name (C{str}), see 

225 property C{.classnaming} and function C{classnaming}. 

226 ''' 

227 return classname(self, prefixed=self._classnaming) 

228 

229 @property_doc_(''' the class naming (C{bool}).''') 

230 def classnaming(self): 

231 '''Get the class naming (C{bool}), see function C{classnaming}. 

232 ''' 

233 return self._classnaming 

234 

235 @classnaming.setter # PYCHOK setter! 

236 def classnaming(self, prefixed): 

237 '''Set the class naming for C{[module.].class} names (C{bool}) 

238 to C{True} to include the module name. 

239 ''' 

240 b = bool(prefixed) 

241 if self._classnaming != b: 

242 self._classnaming = b 

243 _update_attrs(self, *_Named_Property_ROs) 

244 

245 def classof(self, *args, **kwds): 

246 '''Create another instance of this very class. 

247 

248 @arg args: Optional, positional arguments. 

249 @kwarg kwds: Optional, keyword arguments. 

250 

251 @return: New instance (B{self.__class__}). 

252 ''' 

253 return _xnamed(self.__class__(*args, **kwds), self.name) 

254 

255 def copy(self, deep=False, name=NN): 

256 '''Make a shallow or deep copy of this instance. 

257 

258 @kwarg deep: If C{True} make a deep, otherwise 

259 a shallow copy (C{bool}). 

260 @kwarg name: Optional, non-empty name (C{str}). 

261 

262 @return: The copy (C{This class}). 

263 ''' 

264 c = _xcopy(self, deep=deep) 

265 if name: 

266 c.rename(name) 

267 return c 

268 

269 def _DOT_(self, *names): 

270 '''(INTERNAL) Period-join C{self.name} and C{names}. 

271 ''' 

272 return _DOT_(self.name, *names) 

273 

274 def dup(self, deep=False, **items): 

275 '''Duplicate this instance, replacing some attributes. 

276 

277 @kwarg deep: If C{True} duplicate deep, otherwise shallow. 

278 @kwarg items: Attributes to be changed (C{any}). 

279 

280 @return: The duplicate (C{This class}). 

281 

282 @raise AttributeError: Some B{C{items}} invalid. 

283 ''' 

284 n = self.name 

285 m, items = _xkwds_pop2(items, name=n) 

286 d = _xdup(self, deep=deep, **items) 

287 if m != n: 

288 d.rename(m) 

289# if items: 

290# _update_all(d) 

291 return d 

292 

293 def _instr(self, name, prec, *attrs, **fmt_props_kwds): 

294 '''(INTERNAL) Format, used by C{Conic}, C{Ellipsoid}, C{Transform}, C{Triaxial}. 

295 ''' 

296 def _fmt_props_kwds(fmt=Fmt.F, props=(), **kwds): 

297 return fmt, props, kwds 

298 

299 fmt, props, kwds = _fmt_props_kwds(**fmt_props_kwds) 

300 

301 t = () if name is None else (Fmt.EQUAL(name=repr(name or self.name)),) 

302 if attrs: 

303 t += pairs(((a, getattr(self, a)) for a in attrs), 

304 prec=prec, ints=True, fmt=fmt) 

305 if props: 

306 t += pairs(((p.name, getattr(self, p.name)) for p in props), 

307 prec=prec, ints=True) 

308 if kwds: 

309 t += pairs(kwds, prec=prec) 

310 return _COMMASPACE_.join(t) 

311 

312 @property_RO 

313 def iteration(self): # see .karney.GDict 

314 '''Get the most recent iteration number (C{int}) or C{None} 

315 if not available or not applicable. 

316 

317 @note: The interation number may be an aggregate number over 

318 several, nested functions. 

319 ''' 

320 return self._iteration 

321 

322 def methodname(self, which): 

323 '''Get a method C{[module.]class.method} name of this object (C{str}). 

324 

325 @arg which: The method (C{callable}). 

326 ''' 

327 return _DOT_(self.classname, which.__name__ if callable(which) else _NN_) 

328 

329 @property_doc_(''' the name (C{str}).''') 

330 def name(self): 

331 '''Get the name (C{str}). 

332 ''' 

333 return self._name 

334 

335 @name.setter # PYCHOK setter! 

336 def name(self, name): 

337 '''Set the name (C{str}). 

338 

339 @raise NameError: Can't rename, use method L{rename}. 

340 ''' 

341 m, n = self._name, str(name) 

342 if not m: 

343 self._name = n 

344 elif n != m: 

345 n = repr(n) 

346 c = self.classname 

347 t = _DOT_(c, Fmt.PAREN(self.rename.__name__, n)) 

348 n = _DOT_(c, Fmt.EQUALSPACED(name=n)) 

349 m = Fmt.PAREN(_SPACE_('was', repr(m))) 

350 n = _SPACE_(n, m) 

351 raise _NameError(n, txt=_SPACE_('use', t)) 

352 # to set the name from a sub-class, use 

353 # self.name = name or 

354 # _Named.name.fset(self, name), but NOT 

355 # _Named(self).name = name 

356 

357 @Property_RO 

358 def named(self): 

359 '''Get the name I{or} class name or C{""} (C{str}). 

360 ''' 

361 return self.name or self.classname 

362 

363 @Property_RO 

364 def named2(self): 

365 '''Get the C{class} name I{and/or} the name or C{""} (C{str}). 

366 ''' 

367 return _xjoined_(self.classname, self.name) 

368 

369 @Property_RO 

370 def named3(self): 

371 '''Get the I{prefixed} C{class} name I{and/or} the name or C{""} (C{str}). 

372 ''' 

373 return _xjoined_(classname(self, prefixed=True), self.name) 

374 

375 @Property_RO 

376 def named4(self): 

377 '''Get the C{package.module.class} name I{and/or} the name or C{""} (C{str}). 

378 ''' 

379 return _xjoined_(_DOT_(self.__module__, self.__class__.__name__), self.name) 

380 

381 def _notImplemented(self, *args, **kwds): 

382 '''(INTERNAL) See function L{notImplemented}. 

383 ''' 

384 notImplemented(self, *args, **_xkwds(kwds, up=_UP + 1)) 

385 

386 def _notOverloaded(self, *args, **kwds): 

387 '''(INTERNAL) See function L{notOverloaded}. 

388 ''' 

389 notOverloaded(self, *args, **_xkwds(kwds, up=_UP + 1)) 

390 

391 def rename(self, name): 

392 '''Change the name. 

393 

394 @arg name: The new name (C{str}). 

395 

396 @return: The previous name (C{str}). 

397 ''' 

398 m, n = self._name, str(name) 

399 if n != m: 

400 self._name = n 

401 _update_attrs(self, *_Named_Property_ROs) 

402 return m 

403 

404 @property_RO 

405 def sizeof(self): 

406 '''Get the current size in C{bytes} of this instance (C{int}). 

407 ''' 

408 return _sizeof(self) 

409 

410 def toRepr(self, **unused): # PYCHOK no cover 

411 '''Default C{repr(self)}. 

412 ''' 

413 return repr(self) 

414 

415 def toStr(self, **unused): # PYCHOK no cover 

416 '''Default C{str(self)}. 

417 ''' 

418 return str(self) 

419 

420 @deprecated_method 

421 def toStr2(self, **kwds): # PYCHOK no cover 

422 '''DEPRECATED on 23.10.07, use method C{toRepr}.''' 

423 return self.toRepr(**kwds) 

424 

425# def _unstr(self, which, *args, **kwds): 

426# '''(INTERNAL) Return the string representation of a method 

427# invokation of this instance: C{str(self).method(...)} 

428# 

429# @see: Function L{pygeodesy.unstr}. 

430# ''' 

431# return _DOT_(self, unstr(which, *args, **kwds)) 

432 

433 def _xnamed(self, inst, name=NN, force=False): 

434 '''(INTERNAL) Set the instance' C{.name = self.name}. 

435 

436 @arg inst: The instance (C{_Named}). 

437 @kwarg name: Optional name, overriding C{self.name} (C{str}). 

438 @kwarg force: Force name change (C{bool}). 

439 

440 @return: The B{C{inst}}, named if not named before. 

441 ''' 

442 return _xnamed(inst, name or self.name, force=force) 

443 

444 def _xrenamed(self, inst): 

445 '''(INTERNAL) Rename the instance' C{.name = self.name}. 

446 

447 @arg inst: The instance (C{_Named}). 

448 

449 @return: The B{C{inst}}, named if not named before. 

450 

451 @raise TypeError: Not C{isinstance(B{inst}, _Named)}. 

452 ''' 

453 if not isinstance(inst, _Named): 

454 raise _IsnotError(_valid_, inst=inst) 

455 

456 inst.rename(self.name) 

457 return inst 

458 

459_Named_Property_ROs = _allPropertiesOf_n(5, _Named, Property_RO) # PYCHOK once 

460 

461 

462class _NamedBase(_Named): 

463 '''(INTERNAL) Base class with name. 

464 ''' 

465 def __repr__(self): 

466 '''Default C{repr(self)}. 

467 ''' 

468 return self.toRepr() 

469 

470 def __str__(self): 

471 '''Default C{str(self)}. 

472 ''' 

473 return self.toStr() 

474 

475 def others(self, *other, **name_other_up): 

476 '''Refined class comparison, invoked as C{.others(other)}, 

477 C{.others(name=other)} or C{.others(other, name='other')}. 

478 

479 @arg other: The other instance (any C{type}). 

480 @kwarg name_other_up: Overriding C{name=other} and C{up=1} 

481 keyword arguments. 

482 

483 @return: The B{C{other}} iff compatible with this instance's 

484 C{class} or C{type}. 

485 

486 @raise TypeError: Mismatch of the B{C{other}} and this 

487 instance's C{class} or C{type}. 

488 ''' 

489 if other: # most common, just one arg B{C{other}} 

490 other0 = other[0] 

491 if isinstance(other0, self.__class__) or \ 

492 isinstance(self, other0.__class__): 

493 return other0 

494 

495 other, name, up = _xother3(self, other, **name_other_up) 

496 if isinstance(self, other.__class__) or \ 

497 isinstance(other, self.__class__): 

498 return _xnamed(other, name) 

499 

500 raise _xotherError(self, other, name=name, up=up + 1) 

501 

502 def toRepr(self, **kwds): # PYCHOK expected 

503 '''(INTERNAL) I{Could be overloaded}. 

504 

505 @kwarg kwds: Optional, C{toStr} keyword arguments. 

506 

507 @return: C{toStr}() with keyword arguments (as C{str}). 

508 ''' 

509 t = lrstrip(self.toStr(**kwds)) 

510# if self.name: 

511# t = NN(Fmt.EQUAL(name=repr(self.name)), sep, t) 

512 return Fmt.PAREN(self.classname, t) # XXX (self.named, t) 

513 

514# def toRepr(self, **kwds) 

515# if kwds: 

516# s = NN.join(reprs((self,), **kwds)) 

517# else: # super().__repr__ only for Python 3+ 

518# s = super(self.__class__, self).__repr__() 

519# return Fmt.PAREN(self.named, s) # clips(s) 

520 

521 def toStr(self, **kwds): # PYCHOK no cover 

522 '''I{Must be overloaded}.''' 

523 notOverloaded(self, **kwds) 

524 

525# def toStr(self, **kwds): 

526# if kwds: 

527# s = NN.join(strs((self,), **kwds)) 

528# else: # super().__str__ only for Python 3+ 

529# s = super(self.__class__, self).__str__() 

530# return s 

531 

532 def _update(self, updated, *attrs, **setters): 

533 '''(INTERNAL) Zap cached instance attributes and overwrite C{__dict__} or L{Property_RO} values. 

534 ''' 

535 u = _update_all(self, *attrs) if updated else 0 

536 if setters: 

537 d = self.__dict__ 

538 # double-check that setters are Property_RO's 

539 for n, v in setters.items(): 

540 if n in d or _hasProperty(self, n, Property_RO): 

541 d[n] = v 

542 else: 

543 raise _AssertionError(n, v, txt=repr(self)) 

544 u += len(setters) 

545 return u 

546 

547 

548class _NamedDict(ADict, _Named): 

549 '''(INTERNAL) Named C{dict} with key I{and} attribute 

550 access to the items. 

551 ''' 

552 def __init__(self, *args, **kwds): 

553 if args: # args override kwds 

554 if len(args) != 1: # or not isinstance(args[0], dict) 

555 t = unstr(self.classname, *args, **kwds) # PYCHOK no cover 

556 raise _ValueError(args=len(args), txt=t) 

557 kwds = _xkwds(dict(args[0]), **kwds) 

558 n, kwds = _xkwds_pop2(kwds, name=NN) 

559 if n: 

560 _Named.name.fset(self, n) # see _Named.name 

561 ADict.__init__(self, kwds) 

562 

563 def __delattr__(self, name): 

564 '''Delete an attribute or item by B{C{name}}. 

565 ''' 

566 if name in self: # in ADict.keys(self): 

567 ADict.pop(self, name) 

568 elif name in (_name_, _name): 

569 # ADict.__setattr__(self, name, NN) 

570 _Named.rename(self, NN) 

571 else: 

572 ADict.__delattr__(self, name) 

573 

574 def __getattr__(self, name): 

575 '''Get the value of an item by B{C{name}}. 

576 ''' 

577 try: 

578 return self[name] 

579 except KeyError: 

580 if name == _name_: 

581 return _Named.name.fget(self) 

582 raise ADict._AttributeError(self, self._DOT_(name)) 

583 

584 def __getitem__(self, key): 

585 '''Get the value of an item by B{C{key}}. 

586 ''' 

587 if key == _name_: 

588 raise self._KeyError(key) 

589 return ADict.__getitem__(self, key) 

590 

591 def _KeyError(self, key, *value): # PYCHOK no cover 

592 '''(INTERNAL) Create a C{KeyError}. 

593 ''' 

594 n = self.name or self.__class__.__name__ 

595 t = Fmt.SQUARE(n, key) 

596 if value: 

597 t = Fmt.EQUALSPACED(t, *value) 

598 return _KeyError(t) 

599 

600 def __setattr__(self, name, value): 

601 '''Set attribute or item B{C{name}} to B{C{value}}. 

602 ''' 

603 if name in self: # in ADict.keys(self) 

604 ADict.__setitem__(self, name, value) # self[name] = value 

605 else: 

606 ADict.__setattr__(self, name, value) 

607 

608 def __setitem__(self, key, value): 

609 '''Set item B{C{key}} to B{C{value}}. 

610 ''' 

611 if key == _name_: 

612 raise self._KeyError(key, repr(value)) 

613 ADict.__setitem__(self, key, value) 

614 

615 

616class _NamedEnum(_NamedDict): 

617 '''(INTERNAL) Enum-like C{_NamedDict} with attribute access 

618 restricted to valid keys. 

619 ''' 

620 _item_Classes = () 

621 

622 def __init__(self, Class, *Classes, **name): 

623 '''New C{_NamedEnum}. 

624 

625 @arg Class: Initial class or type acceptable as items 

626 values (C{type}). 

627 @arg Classes: Additional, acceptable classes or C{type}s. 

628 ''' 

629 self._item_Classes = (Class,) + Classes 

630 n = _xkwds_get(name, name=NN) or NN(Class.__name__, _s_) 

631 if n and _xvalid(n, underOK=True): 

632 _Named.name.fset(self, n) # see _Named.name 

633 

634 def __getattr__(self, name): 

635 '''Get the value of an attribute or item by B{C{name}}. 

636 ''' 

637 return _NamedDict.__getattr__(self, name) 

638 

639 def __repr__(self): 

640 '''Default C{repr(self)}. 

641 ''' 

642 return self.toRepr() 

643 

644 def __str__(self): 

645 '''Default C{str(self)}. 

646 ''' 

647 return self.toStr() 

648 

649 def _assert(self, **kwds): 

650 '''(INTERNAL) Check attribute name against given, registered name. 

651 ''' 

652 pypy = _isPyPy() 

653 for n, v in kwds.items(): 

654 if isinstance(v, _LazyNamedEnumItem): # property 

655 assert (n == v.name) if pypy else (n is v.name) 

656 # assert not hasattr(self.__class__, n) 

657 setattr(self.__class__, n, v) 

658 elif isinstance(v, self._item_Classes): # PYCHOK no cover 

659 assert self[n] is v and getattr(self, n) \ 

660 and self.find(v) == n 

661 else: 

662 raise _TypeError(v, name=n) 

663 

664 def find(self, item, dflt=None, all=False): 

665 '''Find a registered item. 

666 

667 @arg item: The item to look for (any C{type}). 

668 @kwarg dflt: Value to return if not found (any C{type}). 

669 @kwarg all: Use C{True} to search I{all} items or C{False} only 

670 the currently I{registered} ones (C{bool}). 

671 

672 @return: The B{C{item}}'s name if found (C{str}), or C{{dflt}} 

673 if there is no such B{C{item}}. 

674 ''' 

675 for k, v in self.items(all=all): # or ADict.items(self) 

676 if v is item: 

677 return k 

678 return dflt 

679 

680 def get(self, name, dflt=None): 

681 '''Get the value of a I{registered} item. 

682 

683 @arg name: The name of the item (C{str}). 

684 @kwarg dflt: Value to return (any C{type}). 

685 

686 @return: The item with B{C{name}} if found, or B{C{dflt}} if 

687 there is no I{registered} item with that B{C{name}}. 

688 ''' 

689 # getattr needed to instantiate L{_LazyNamedEnumItem} 

690 return getattr(self, name, dflt) 

691 

692 def items(self, all=False, asorted=False): 

693 '''Yield all or only the I{registered} items. 

694 

695 @kwarg all: Use C{True} to yield I{all} items or C{False} for 

696 only the currently I{registered} ones (C{bool}). 

697 @kwarg asorted: If C{True}, yield the items in I{alphabetical, 

698 case-insensitive} order (C{bool}). 

699 ''' 

700 if all: # instantiate any remaining L{_LazyNamedEnumItem} 

701 for n, p in tuple(self.__class__.__dict__.items()): 

702 if isinstance(p, _LazyNamedEnumItem): 

703 _ = getattr(self, n) 

704 return itemsorted(self) if asorted else ADict.items(self) 

705 

706 def keys(self, **all_asorted): 

707 '''Yield the name (C{str}) of I{all} or only the currently I{registered} 

708 items, optionally sorted I{alphabetically, case-insensitively}. 

709 

710 @kwarg all_asorted: See method C{items}. 

711 ''' 

712 for k, _ in self.items(**all_asorted): 

713 yield k 

714 

715 def popitem(self): 

716 '''Remove I{an, any} currently I{registed} item. 

717 

718 @return: The removed item. 

719 ''' 

720 return self._zapitem(*ADict.popitem(self)) 

721 

722 def register(self, item): 

723 '''Registed one new item or I{all} or I{any} unregistered ones. 

724 

725 @arg item: The item (any C{type}) or B{I{all}} or B{C{any}}. 

726 

727 @return: The item name (C{str}) or C("all") or C{"any"}. 

728 

729 @raise NameError: An B{C{item}} with that name is already 

730 registered the B{C{item}} has no or an 

731 invalid name. 

732 

733 @raise TypeError: The B{C{item}} type invalid. 

734 ''' 

735 if item is all or item is any: 

736 _ = self.items(all=True) 

737 n = item.__name__ 

738 else: 

739 try: 

740 n = item.name 

741 if not (n and isstr(n) and isidentifier(n)): 

742 raise ValueError() 

743 except (AttributeError, ValueError, TypeError) as x: 

744 raise _NameError(_DOT_(_item_, _name_), item, cause=x) 

745 if n in self: 

746 t = _SPACE_(_item_, self._DOT_(n), _exists_) 

747 raise _NameError(t, txt=repr(item)) 

748 if not isinstance(item, self._item_Classes): 

749 raise _TypesError(self._DOT_(n), item, *self._item_Classes) 

750 self[n] = item 

751 return n 

752 

753 def unregister(self, name_or_item): 

754 '''Remove a I{registered} item. 

755 

756 @arg name_or_item: Name (C{str}) or the item (any C{type}). 

757 

758 @return: The unregistered item. 

759 

760 @raise AttributeError: No such B{C{item}}. 

761 

762 @raise NameError: No item with that B{C{name}}. 

763 ''' 

764 if isstr(name_or_item): 

765 name = name_or_item 

766 else: 

767 name = self.find(name_or_item, dflt=MISSING) # all=True? 

768 if name is MISSING: 

769 t = _SPACE_(_no_, 'such', self.classname, _item_) 

770 raise _AttributeError(t, txt=repr(name_or_item)) 

771 try: 

772 item = ADict.pop(self, name) 

773 except KeyError: 

774 raise _NameError(item=self._DOT_(name), txt=_doesn_t_exist_) 

775 return self._zapitem(name, item) 

776 

777 pop = unregister 

778 

779 def toRepr(self, prec=6, fmt=Fmt.F, sep=_COMMANL_, **all_asorted): # PYCHOK _NamedDict, ADict 

780 '''Like C{repr(dict)} but C{name}s optionally sorted and 

781 C{floats} formatted by function L{pygeodesy.fstr}. 

782 ''' 

783 t = ((self._DOT_(n), v) for n, v in self.items(**all_asorted)) 

784 return sep.join(pairs(t, prec=prec, fmt=fmt, sep=_COLONSPACE_)) 

785 

786 def toStr(self, *unused, **all_asorted): # PYCHOK _NamedDict, ADict 

787 '''Return a string with all C{name}s, optionally sorted. 

788 ''' 

789 return self._DOT_(_COMMASPACEDOT_.join(self.keys(**all_asorted))) 

790 

791 def values(self, **all_asorted): 

792 '''Yield the value (C{type}) of all or only the I{registered} items, 

793 optionally sorted I{alphabetically} and I{case-insensitively}. 

794 

795 @kwarg all_asorted: See method C{items}. 

796 ''' 

797 for _, v in self.items(**all_asorted): 

798 yield v 

799 

800 def _zapitem(self, name, item): 

801 # remove _LazyNamedEnumItem property value if still present 

802 if self.__dict__.get(name, None) is item: 

803 self.__dict__.pop(name) # [name] = None 

804 item._enum = None 

805 return item 

806 

807 

808class _LazyNamedEnumItem(property_RO): # XXX or descriptor? 

809 '''(INTERNAL) Lazily instantiated L{_NamedEnumItem}. 

810 ''' 

811 pass 

812 

813 

814def _lazyNamedEnumItem(name, *args, **kwds): 

815 '''(INTERNAL) L{_LazyNamedEnumItem} property-like factory. 

816 

817 @see: Luciano Ramalho, "Fluent Python", O'Reilly, Example 

818 19-24, 2016 p. 636 or Example 22-28, 2022 p. 869+ 

819 ''' 

820 def _fget(inst): 

821 # assert isinstance(inst, _NamedEnum) 

822 try: # get the item from the instance' __dict__ 

823 # item = inst.__dict__[name] # ... or ADict 

824 item = inst[name] 

825 except KeyError: 

826 # instantiate an _NamedEnumItem, it self-registers 

827 item = inst._Lazy(*args, **_xkwds(kwds, name=name)) 

828 # assert inst[name] is item # MUST be registered 

829 # store the item in the instance' __dict__ ... 

830 # inst.__dict__[name] = item # ... or update the 

831 inst.update({name: item}) # ... ADict for Triaxials 

832 # remove the property from the registry class, such that 

833 # (a) the property no longer overrides the instance' item 

834 # in inst.__dict__ and (b) _NamedEnum.items(all=True) only 

835 # sees any un-instantiated ones yet to be instantiated 

836 p = getattr(inst.__class__, name, None) 

837 if isinstance(p, _LazyNamedEnumItem): 

838 delattr(inst.__class__, name) 

839 # assert isinstance(item, _NamedEnumItem) 

840 return item 

841 

842 p = _LazyNamedEnumItem(_fget) 

843 p.name = name 

844 return p 

845 

846 

847class _NamedEnumItem(_NamedBase): 

848 '''(INTERNAL) Base class for items in a C{_NamedEnum} registery. 

849 ''' 

850 _enum = None 

851 

852# def __ne__(self, other): # XXX fails for Lcc.conic = conic! 

853# '''Compare this and an other item. 

854# 

855# @return: C{True} if different, C{False} otherwise. 

856# ''' 

857# return not self.__eq__(other) 

858 

859 @property_doc_(''' the I{registered} name (C{str}).''') 

860 def name(self): 

861 '''Get the I{registered} name (C{str}). 

862 ''' 

863 return self._name 

864 

865 @name.setter # PYCHOK setter! 

866 def name(self, name): 

867 '''Set the name, unless already registered (C{str}). 

868 ''' 

869 if self._enum: 

870 raise _NameError(str(name), self, txt=_registered_) # XXX _TypeError 

871 self._name = str(name) 

872 

873 def _register(self, enum, name): 

874 '''(INTERNAL) Add this item as B{C{enum.name}}. 

875 

876 @note: Don't register if name is empty or doesn't 

877 start with a letter. 

878 ''' 

879 if name and _xvalid(name, underOK=True): 

880 self.name = name 

881 if name[:1].isalpha(): # '_...' not registered 

882 enum.register(self) 

883 self._enum = enum 

884 

885 def unregister(self): 

886 '''Remove this instance from its C{_NamedEnum} registry. 

887 

888 @raise AssertionError: Mismatch of this and registered item. 

889 

890 @raise NameError: This item is unregistered. 

891 ''' 

892 enum = self._enum 

893 if enum and self.name and self.name in enum: 

894 item = enum.unregister(self.name) 

895 if item is not self: 

896 t = _SPACE_(repr(item), _vs_, repr(self)) # PYCHOK no cover 

897 raise _AssertionError(t) 

898 

899 

900class _NamedTuple(tuple, _Named): 

901 '''(INTERNAL) Base for named C{tuple}s with both index I{and} 

902 attribute name access to the items. 

903 

904 @note: This class is similar to Python's C{namedtuple}, 

905 but statically defined, lighter and limited. 

906 ''' 

907 _Names_ = () # item names, non-identifier, no leading underscore 

908 '''Tuple specifying the C{name} of each C{Named-Tuple} item. 

909 

910 @note: Specify at least 2 item names. 

911 ''' 

912 _Units_ = () # .units classes 

913 '''Tuple defining the C{units} of the value of each C{Named-Tuple} item. 

914 

915 @note: The C{len(_Units_)} must match C{len(_Names_)}. 

916 ''' 

917 _validated = False # set to True I{per sub-class!} 

918 

919 def __new__(cls, arg, *args, **iteration_name): 

920 '''New L{_NamedTuple} initialized with B{C{positional}} arguments. 

921 

922 @arg arg: Tuple items (C{tuple}, C{list}, ...) or first tuple 

923 item of several more in other positional arguments. 

924 @arg args: Tuple items (C{any}), all positional arguments. 

925 @kwarg iteration_name: Only keyword arguments C{B{iteration}=None} 

926 and C{B{name}=NN} are used, any other are 

927 I{silently} ignored. 

928 

929 @raise LenError: Unequal number of positional arguments and 

930 number of item C{_Names_} or C{_Units_}. 

931 

932 @raise TypeError: The C{_Names_} or C{_Units_} attribute is 

933 not a C{tuple} of at least 2 items. 

934 

935 @raise ValueError: Item name is not a C{str} or valid C{identifier} 

936 or starts with C{underscore}. 

937 ''' 

938 n, args = len2(((arg,) + args) if args else arg) 

939 self = tuple.__new__(cls, args) 

940 if not self._validated: 

941 self._validate() 

942 

943 N = len(self._Names_) 

944 if n != N: 

945 raise LenError(self.__class__, args=n, _Names_=N) 

946 

947 if iteration_name: 

948 self._kwdself(**iteration_name) 

949 return self 

950 

951 def __delattr__(self, name): 

952 '''Delete an attribute by B{C{name}}. 

953 

954 @note: Items can not be deleted. 

955 ''' 

956 if name in self._Names_: 

957 raise _TypeError(_del_, _DOT_(self.classname, name), txt=_immutable_) 

958 elif name in (_name_, _name): 

959 _Named.__setattr__(self, name, NN) # XXX _Named.name.fset(self, NN) 

960 else: 

961 tuple.__delattr__(self, name) 

962 

963 def __getattr__(self, name): 

964 '''Get the value of an attribute or item by B{C{name}}. 

965 ''' 

966 try: 

967 return tuple.__getitem__(self, self._Names_.index(name)) 

968 except IndexError: 

969 raise _IndexError(_DOT_(self.classname, Fmt.ANGLE(_name_)), name) 

970 except ValueError: # e.g. _iteration 

971 return tuple.__getattribute__(self, name) 

972 

973# def __getitem__(self, index): # index, slice, etc. 

974# '''Get the item(s) at an B{C{index}} or slice. 

975# ''' 

976# return tuple.__getitem__(self, index) 

977 

978 def __hash__(self): 

979 return tuple.__hash__(self) 

980 

981 def __repr__(self): 

982 '''Default C{repr(self)}. 

983 ''' 

984 return self.toRepr() 

985 

986 def __setattr__(self, name, value): 

987 '''Set attribute or item B{C{name}} to B{C{value}}. 

988 ''' 

989 if name in self._Names_: 

990 raise _TypeError(_DOT_(self.classname, name), value, txt=_immutable_) 

991 elif name in (_name_, _name): 

992 _Named.__setattr__(self, name, value) # XXX _Named.name.fset(self, value) 

993 else: # e.g. _iteration 

994 tuple.__setattr__(self, name, value) 

995 

996 def __str__(self): 

997 '''Default C{repr(self)}. 

998 ''' 

999 return self.toStr() 

1000 

1001 def dup(self, name=NN, **items): 

1002 '''Duplicate this tuple replacing one or more items. 

1003 

1004 @kwarg name: Optional new name (C{str}). 

1005 @kwarg items: Items to be replaced (C{name=value} pairs), if any. 

1006 

1007 @return: A copy of this tuple with B{C{items}}. 

1008 

1009 @raise NameError: Some B{C{items}} invalid. 

1010 ''' 

1011 tl = list(self) 

1012 if items: 

1013 _ix = self._Names_.index 

1014 try: 

1015 for n, v in items.items(): 

1016 tl[_ix(n)] = v 

1017 except ValueError: # bad item name 

1018 raise _NameError(_DOT_(self.classname, n), v, this=self) 

1019 return self.classof(*tl, name=name or self.name) 

1020 

1021 def items(self): 

1022 '''Yield the items, each as a C{(name, value)} pair (C{2-tuple}). 

1023 

1024 @see: Method C{.units}. 

1025 ''' 

1026 for n, v in _zip(self._Names_, self): # strict=True 

1027 yield n, v 

1028 

1029 iteritems = items 

1030 

1031 def _kwdself(self, iteration=None, name=NN, **unused): 

1032 '''(INTERNAL) Set C{__new__} keyword arguments. 

1033 ''' 

1034 if iteration is not None: 

1035 self._iteration = iteration 

1036 if name: 

1037 self.name = name 

1038 

1039 def toRepr(self, prec=6, sep=_COMMASPACE_, fmt=Fmt.F, **unused): # PYCHOK signature 

1040 '''Return this C{Named-Tuple} items as C{name=value} string(s). 

1041 

1042 @kwarg prec: The C{float} precision, number of decimal digits (0..9). 

1043 Trailing zero decimals are stripped for B{C{prec}} values 

1044 of 1 and above, but kept for negative B{C{prec}} values. 

1045 @kwarg sep: Separator to join (C{str}). 

1046 @kwarg fmt: Optional C{float} format (C{letter}). 

1047 

1048 @return: Tuple items (C{str}). 

1049 ''' 

1050 t = pairs(self.items(), prec=prec, fmt=fmt) 

1051# if self.name: 

1052# t = (Fmt.EQUAL(name=repr(self.name)),) + t 

1053 return Fmt.PAREN(self.named, sep.join(t)) # XXX (self.classname, sep.join(t)) 

1054 

1055 def toStr(self, prec=6, sep=_COMMASPACE_, fmt=Fmt.F, **unused): # PYCHOK signature 

1056 '''Return this C{Named-Tuple} items as string(s). 

1057 

1058 @kwarg prec: The C{float} precision, number of decimal digits (0..9). 

1059 Trailing zero decimals are stripped for B{C{prec}} values 

1060 of 1 and above, but kept for negative B{C{prec}} values. 

1061 @kwarg sep: Separator to join (C{str}). 

1062 @kwarg fmt: Optional C{float} format (C{letter}). 

1063 

1064 @return: Tuple items (C{str}). 

1065 ''' 

1066 return Fmt.PAREN(sep.join(reprs(self, prec=prec, fmt=fmt))) 

1067 

1068 def toUnits(self, Error=UnitError): # overloaded in .frechet, .hausdorff 

1069 '''Return a copy of this C{Named-Tuple} with each item value wrapped 

1070 as an instance of its L{units} class. 

1071 

1072 @kwarg Error: Error to raise for L{units} issues (C{UnitError}). 

1073 

1074 @return: A duplicate of this C{Named-Tuple} (C{C{Named-Tuple}}). 

1075 

1076 @raise Error: Invalid C{Named-Tuple} item or L{units} class. 

1077 ''' 

1078 t = (v for _, v in self.units(Error=Error)) 

1079 return self.classof(*tuple(t)) 

1080 

1081 def units(self, Error=UnitError): 

1082 '''Yield the items, each as a C{(name, value}) pair (C{2-tuple}) with 

1083 the value wrapped as an instance of its L{units} class. 

1084 

1085 @kwarg Error: Error to raise for L{units} issues (C{UnitError}). 

1086 

1087 @raise Error: Invalid C{Named-Tuple} item or L{units} class. 

1088 

1089 @see: Method C{.items}. 

1090 ''' 

1091 for n, v, U in _zip(self._Names_, self, self._Units_): # strict=True 

1092 if not (v is None or U is None 

1093 or (isclass(U) and 

1094 isinstance(v, U) and 

1095 hasattr(v, _name_) and 

1096 v.name == n)): # PYCHOK indent 

1097 v = U(v, name=n, Error=Error) 

1098 yield n, v 

1099 

1100 iterunits = units 

1101 

1102 def _validate(self, underOK=False): # see .EcefMatrix 

1103 '''(INTERNAL) One-time check of C{_Names_} and C{_Units_} 

1104 for each C{_NamedUnit} I{sub-class separately}. 

1105 ''' 

1106 ns = self._Names_ 

1107 if not (isinstance(ns, tuple) and len(ns) > 1): # XXX > 0 

1108 raise _TypeError(_DOT_(self.classname, _Names_), ns) 

1109 for i, n in enumerate(ns): 

1110 if not _xvalid(n, underOK=underOK): 

1111 t = Fmt.SQUARE(_Names_=i) # PYCHOK no cover 

1112 raise _ValueError(_DOT_(self.classname, t), n) 

1113 

1114 us = self._Units_ 

1115 if not isinstance(us, tuple): 

1116 raise _TypeError(_DOT_(self.classname, _Units_), us) 

1117 if len(us) != len(ns): 

1118 raise LenError(self.__class__, _Units_=len(us), _Names_=len(ns)) 

1119 for i, u in enumerate(us): 

1120 if not (u is None or callable(u)): 

1121 t = Fmt.SQUARE(_Units_=i) # PYCHOK no cover 

1122 raise _TypeError(_DOT_(self.classname, t), u) 

1123 

1124 self.__class__._validated = True 

1125 

1126 def _xtend(self, xTuple, *items, **name): 

1127 '''(INTERNAL) Extend this C{Named-Tuple} with C{items} to an other B{C{xTuple}}. 

1128 ''' 

1129 if (issubclassof(xTuple, _NamedTuple) and 

1130 (len(self._Names_) + len(items)) == len(xTuple._Names_) and 

1131 self._Names_ == xTuple._Names_[:len(self)]): 

1132 return xTuple(self + items, **_xkwds(name, name=self.name)) # *(self + items) 

1133 c = NN(self.classname, repr(self._Names_)) # PYCHOK no cover 

1134 x = NN(xTuple.__name__, repr(xTuple._Names_)) # PYCHOK no cover 

1135 raise TypeError(_SPACE_(c, _vs_, x)) 

1136 

1137 

1138def callername(up=1, dflt=NN, source=False, underOK=False): 

1139 '''Get the name of the invoking callable. 

1140 

1141 @kwarg up: Number of call stack frames up (C{int}). 

1142 @kwarg dflt: Default return value (C{any}). 

1143 @kwarg source: Include source file name and line number (C{bool}). 

1144 @kwarg underOK: If C{True}, private, internal callables are OK, 

1145 otherwise private callables are skipped (C{bool}). 

1146 

1147 @return: The callable name (C{str}) or B{C{dflt}} if none found. 

1148 ''' 

1149 try: # see .lazily._caller3 

1150 for u in range(up, up + 32): 

1151 n, f, s = _caller3(u) 

1152 if n and (underOK or n.startswith(_DUNDER_) or 

1153 not n.startswith(_UNDER_)): 

1154 if source: 

1155 n = NN(n, _AT_, f, _COLON_, str(s)) 

1156 return n 

1157 except (AttributeError, ValueError): 

1158 pass 

1159 return dflt 

1160 

1161 

1162def _callername2(args, callername=NN, source=False, underOK=False, up=_UP, **kwds): 

1163 '''(INTERNAL) Extract C{callername}, C{source}, C{underOK} and C{up} from C{kwds}. 

1164 ''' 

1165 n = callername or _MODS.named.callername(up=up + 1, source=source, 

1166 underOK=underOK or bool(args or kwds)) 

1167 return n, kwds 

1168 

1169 

1170def _callname(name, class_name, self_name, up=1): 

1171 '''(INTERNAL) Assemble the name for an invokation. 

1172 ''' 

1173 n, c = class_name, callername(up=up + 1) 

1174 if c: 

1175 n = _DOT_(n, Fmt.PAREN(c, name)) 

1176 if self_name: 

1177 n = _SPACE_(n, repr(self_name)) 

1178 return n 

1179 

1180 

1181def classname(inst, prefixed=None): 

1182 '''Return the instance' class name optionally prefixed with the 

1183 module name. 

1184 

1185 @arg inst: The object (any C{type}). 

1186 @kwarg prefixed: Include the module name (C{bool}), see 

1187 function C{classnaming}. 

1188 

1189 @return: The B{C{inst}}'s C{[module.]class} name (C{str}). 

1190 ''' 

1191 if prefixed is None: 

1192 prefixed = getattr(inst, classnaming.__name__, prefixed) 

1193 return modulename(inst.__class__, prefixed=prefixed) 

1194 

1195 

1196def classnaming(prefixed=None): 

1197 '''Get/set the default class naming for C{[module.]class} names. 

1198 

1199 @kwarg prefixed: Include the module name (C{bool}). 

1200 

1201 @return: Previous class naming setting (C{bool}). 

1202 ''' 

1203 t = _Named._classnaming 

1204 if prefixed in (True, False): 

1205 _Named._classnaming = prefixed 

1206 return t 

1207 

1208 

1209def modulename(clas, prefixed=None): # in .basics._xversion 

1210 '''Return the class name optionally prefixed with the 

1211 module name. 

1212 

1213 @arg clas: The class (any C{class}). 

1214 @kwarg prefixed: Include the module name (C{bool}), see 

1215 function C{classnaming}. 

1216 

1217 @return: The B{C{class}}'s C{[module.]class} name (C{str}). 

1218 ''' 

1219 try: 

1220 n = clas.__name__ 

1221 except AttributeError: 

1222 n = '__name__' # _DUNDER_(NN, _name_, NN) 

1223 if prefixed or (classnaming() if prefixed is None else False): 

1224 try: 

1225 m = clas.__module__.rsplit(_DOT_, 1) 

1226 n = _DOT_.join(m[1:] + [n]) 

1227 except AttributeError: 

1228 pass 

1229 return n 

1230 

1231 

1232def nameof(inst): 

1233 '''Get the name of an instance. 

1234 

1235 @arg inst: The object (any C{type}). 

1236 

1237 @return: The instance' name (C{str}) or C{""}. 

1238 ''' 

1239 n = _xattr(inst, name=NN) 

1240 if not n: # and isinstance(inst, property): 

1241 try: 

1242 n = inst.fget.__name__ 

1243 except AttributeError: 

1244 n = NN 

1245 return n 

1246 

1247 

1248def _notDecap(where): 

1249 '''De-Capitalize C{where.__name__}. 

1250 ''' 

1251 n = where.__name__ 

1252 c = n[3].lower() # len(_not_) 

1253 return NN(n[:3], _SPACE_, c, n[4:]) 

1254 

1255 

1256def _notError(inst, name, args, kwds): # PYCHOK no cover 

1257 '''(INTERNAL) Format an error message. 

1258 ''' 

1259 n = _DOT_(classname(inst, prefixed=True), _dunder_nameof(name, name)) 

1260 m = _COMMASPACE_.join(modulename(c, prefixed=True) for c in inst.__class__.__mro__[1:-1]) 

1261 return _COMMASPACE_(unstr(n, *args, **kwds), Fmt.PAREN(_MRO_, m)) 

1262 

1263 

1264def _NotImplemented(inst, *other, **kwds): 

1265 '''(INTERNAL) Raise a C{__special__} error or return C{NotImplemented}, 

1266 but only if env variable C{PYGEODESY_NOTIMPLEMENTED=std}. 

1267 ''' 

1268 if _std_NotImplemented: 

1269 return NotImplemented 

1270 n, kwds = _callername2(other, **kwds) # source=True 

1271 t = unstr(_DOT_(classname(inst), n), *other, **kwds) 

1272 raise _NotImplementedError(t, txt=repr(inst)) 

1273 

1274 

1275def notImplemented(inst, *args, **kwds): # PYCHOK no cover 

1276 '''Raise a C{NotImplementedError} for a missing instance method or 

1277 property or for a missing caller feature. 

1278 

1279 @arg inst: Caller instance (C{any}) or C{None} for function. 

1280 @arg args: Method or property positional arguments (any C{type}s). 

1281 @arg kwds: Method or property keyword arguments (any C{type}s), 

1282 except C{B{callername}=NN}, C{B{underOK}=False} and 

1283 C{B{up}=2}. 

1284 ''' 

1285 n, kwds = _callername2(args, **kwds) 

1286 t = _notError(inst, n, args, kwds) if inst else unstr(n, *args, **kwds) 

1287 raise _NotImplementedError(t, txt=_notDecap(notImplemented)) 

1288 

1289 

1290def notOverloaded(inst, *args, **kwds): # PYCHOK no cover 

1291 '''Raise an C{AssertionError} for a method or property not overloaded. 

1292 

1293 @arg inst: Instance (C{any}). 

1294 @arg args: Method or property positional arguments (any C{type}s). 

1295 @arg kwds: Method or property keyword arguments (any C{type}s), 

1296 except C{B{callername}=NN}, C{B{underOK}=False} and 

1297 C{B{up}=2}. 

1298 ''' 

1299 n, kwds = _callername2(args, **kwds) 

1300 t = _notError(inst, n, args, kwds) 

1301 raise _AssertionError(t, txt=_notDecap(notOverloaded)) 

1302 

1303 

1304def _Pass(arg, **unused): # PYCHOK no cover 

1305 '''(INTERNAL) I{Pass-thru} class for C{_NamedTuple._Units_}. 

1306 ''' 

1307 return arg 

1308 

1309 

1310__all__ += _ALL_DOCS(_Named, 

1311 _NamedBase, # _NamedDict, 

1312 _NamedEnum, _NamedEnumItem, 

1313 _NamedTuple) 

1314 

1315# **) MIT License 

1316# 

1317# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved. 

1318# 

1319# Permission is hereby granted, free of charge, to any person obtaining a 

1320# copy of this software and associated documentation files (the "Software"), 

1321# to deal in the Software without restriction, including without limitation 

1322# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

1323# and/or sell copies of the Software, and to permit persons to whom the 

1324# Software is furnished to do so, subject to the following conditions: 

1325# 

1326# The above copyright notice and this permission notice shall be included 

1327# in all copies or substantial portions of the Software. 

1328# 

1329# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

1330# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

1331# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

1332# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

1333# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

1334# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

1335# OTHER DEALINGS IN THE SOFTWARE.