Coverage for pygeodesy/named.py: 96%

454 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-03-03 11:31 -0500

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, LenError, _NameError, \ 

20 _NotImplementedError, _TypeError, _TypesError, \ 

21 _ValueError, UnitError, _xattr, _xkwds, _xkwds_get, \ 

22 _xkwds_item2, _xkwds_pop2 

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

24 _COMMASPACE_, _doesn_t_exist_, _DOT_, _DUNDER_, \ 

25 _EQUAL_, _EQUALSPACED_, _exists_, _immutable_, _name_, \ 

26 _NL_, _NN_, _not_, _other_, _s_, _SPACE_, _std_, \ 

27 _UNDER_, _valid_, _vs_, _dunder_nameof, _isPyPy, _under 

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

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

30 _update_all, property_doc_, Property_RO, property_RO, \ 

31 _update_attrs 

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

33 

34__all__ = _ALL_LAZY.named 

35__version__ = '24.02.27' 

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 

49 

50def _xjoined_(prefix, name): 

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

52 ''' 

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

54 

55 

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

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

58 

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

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

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

62 

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

64 not named before. 

65 ''' 

66 if name and isinstance(inst, _Named): 

67 if not inst.name: 

68 inst.name = name 

69 elif force: 

70 inst.rename(name) 

71 return inst 

72 

73 

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

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

76 ''' 

77 if name_other: # and not other and len(name_other) == 1 

78 name, other = _xkwds_item2(name_other) 

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

80 other = other[0] 

81 else: 

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

83 return other, name, up 

84 

85 

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

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

88 ''' 

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

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

91 

92 

93def _xvalid(name, _OK=False): 

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

95 ''' 

96 return True if (name and isstr(name) 

97 and name != _name_ 

98 and (_OK or not name.startswith(_UNDER_)) 

99 and (not iskeyword(name)) 

100 and isidentifier(name)) else False 

101 

102 

103class ADict(dict): 

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

105 the C{dict} items. 

106 ''' 

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

108 

109 def __getattr__(self, name): 

110 '''Get an attribute or item by B{C{name}}. 

111 ''' 

112 try: 

113 return self[name] 

114 except KeyError: 

115 pass 

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

117 raise _AttributeError(item=name, txt=_doesn_t_exist_) 

118 

119 def __repr__(self): 

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

121 ''' 

122 return self.toRepr() 

123 

124 def __str__(self): 

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

126 ''' 

127 return self.toStr() 

128 

129 @property_RO 

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

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

132 C{None} if not available/applicable. 

133 ''' 

134 return self._iteration 

135 

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

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

138 

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

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

141 ''' 

142 if iteration is not None: 

143 self._iteration = iteration 

144 dict.update(self, items) 

145 return self # in .rhumbBase.RhumbLineBase 

146 

147 def toRepr(self, **prec_fmt): # PYCHOK signature 

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

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

150 ''' 

151 n = _xkwds_get(self, name=classname(self)) 

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

153 

154 def toStr(self, **prec_fmt): # PYCHOK signature 

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

156 function L{pygeodesy.fstr}. 

157 ''' 

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

159 

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

161 '''(INTERNAL) Helper for C{.toRepr} and C{.toStr}, also 

162 in C{_NamedDict} below. 

163 ''' 

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

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

166 

167 

168class _Named(object): 

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

170 ''' 

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

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

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

174# _updates = 0 # OBSOLETE Property/property updates 

175 

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

177 '''Not implemented.''' 

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

179 

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

181 '''Not implemented.''' 

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

183 

184 def __repr__(self): 

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

186 ''' 

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

188 

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

190 '''Not implemented.''' 

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

192 

193 def __str__(self): 

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

195 ''' 

196 return self.named2 

197 

198 def attrs(self, *names, **sep_COMMASPACE__Nones_True__pairs_kwds): 

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

200 function L{pygeodesy.fstr}. 

201 

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

203 @kwarg sep_COMMASPACE__Nones_True__pairs_kwds: Keyword argument for function 

204 L{pygeodesy.pairs}, except C{B{sep}=", "} and C{B{Nones}=True} to 

205 in- or exclude missing or C{None}-valued attributes. 

206 

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

208 

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

210 ''' 

211 def _sep_kwds(sep=_COMMASPACE_, **kwds): 

212 return sep, kwds 

213 

214 sep, kwds = _sep_kwds(**sep_COMMASPACE__Nones_True__pairs_kwds) 

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

216 

217 @Property_RO 

218 def classname(self): 

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

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

221 ''' 

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

223 

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

225 def classnaming(self): 

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

227 ''' 

228 return self._classnaming 

229 

230 @classnaming.setter # PYCHOK setter! 

231 def classnaming(self, prefixed): 

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

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

234 ''' 

235 b = bool(prefixed) 

236 if self._classnaming != b: 

237 self._classnaming = b 

238 _update_attrs(self, *_Named_Property_ROs) 

239 

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

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

242 

243 @arg args: Optional, positional arguments. 

244 @kwarg kwds: Optional, keyword arguments. 

245 

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

247 ''' 

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

249 

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

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

252 

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

254 a shallow copy (C{bool}). 

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

256 

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

258 ''' 

259 c = _xcopy(self, deep=deep) 

260 if name: 

261 c.rename(name) 

262 return c 

263 

264 def _DOT_(self, *names): 

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

266 ''' 

267 return _DOT_(self.name, *names) 

268 

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

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

271 

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

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

274 

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

276 

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

278 ''' 

279 n = self.name 

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

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

282 if m != n: 

283 d.rename(m) 

284# if items: 

285# _update_all(d) 

286 return d 

287 

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

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

290 ''' 

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

292 return fmt, props, kwds 

293 

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

295 

296 t = Fmt.EQUAL(_name_, repr(name or self.name)), 

297 if attrs: 

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

299 prec=prec, fmt=fmt, ints=True) 

300 if props: 

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

302 prec=prec, ints=True) 

303 if kwds: 

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

305 return _COMMASPACE_.join(t[1:] if name is None else t) 

306 

307 @property_RO 

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

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

310 if not available or not applicable. 

311 

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

313 several, nested functions. 

314 ''' 

315 return self._iteration 

316 

317 def methodname(self, which): 

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

319 

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

321 ''' 

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

323 

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

325 def name(self): 

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

327 ''' 

328 return self._name 

329 

330 @name.setter # PYCHOK setter! 

331 def name(self, name): 

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

333 

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

335 ''' 

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

337 if not m: 

338 self._name = n 

339 elif n != m: 

340 n = repr(n) 

341 c = self.classname 

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

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

344 n = _DOT_(c, _EQUALSPACED_(_name_, n)) 

345 n = _SPACE_(n, m) 

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

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

348 # self.name = name or 

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

350 # _Named(self).name = name 

351 

352 @Property_RO 

353 def named(self): 

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

355 ''' 

356 return self.name or self.classname 

357 

358 @Property_RO 

359 def named2(self): 

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

361 ''' 

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

363 

364 @Property_RO 

365 def named3(self): 

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

367 ''' 

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

369 

370 @Property_RO 

371 def named4(self): 

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

373 ''' 

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

375 

376 def rename(self, name): 

377 '''Change the name. 

378 

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

380 

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

382 ''' 

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

384 if n != m: 

385 self._name = n 

386 _update_attrs(self, *_Named_Property_ROs) 

387 return m 

388 

389 @property_RO 

390 def sizeof(self): 

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

392 ''' 

393 return _sizeof(self) 

394 

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

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

397 ''' 

398 return repr(self) 

399 

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

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

402 ''' 

403 return str(self) 

404 

405 @deprecated_method 

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

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

408 return self.toRepr(**kwds) 

409 

410 def _unstr(self, which, *args, **kwds): 

411 '''(INTERNAL) Return the string representation of a method 

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

413 

414 @see: Function L{pygeodesy.unstr}. 

415 ''' 

416 n = _DOT_(self, which.__name__ if callable(which) else _NN_) 

417 return unstr(n, *args, **kwds) 

418 

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

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

421 

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

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

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

425 

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

427 ''' 

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

429 

430 def _xrenamed(self, inst): 

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

432 

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

434 

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

436 

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

438 ''' 

439 if not isinstance(inst, _Named): 

440 raise _IsnotError(_valid_, inst=inst) 

441 

442 inst.rename(self.name) 

443 return inst 

444 

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

446 

447 

448class _NamedBase(_Named): 

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

450 ''' 

451 def __repr__(self): 

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

453 ''' 

454 return self.toRepr() 

455 

456 def __str__(self): 

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

458 ''' 

459 return self.toStr() 

460 

461# def notImplemented(self, attr): 

462# '''Raise error for a missing method, function or attribute. 

463# 

464# @arg attr: Attribute name (C{str}). 

465# 

466# @raise NotImplementedError: No such attribute. 

467# ''' 

468# c = self.__class__.__name__ 

469# return NotImplementedError(_DOT_(c, attr)) 

470 

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

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

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

474 

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

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

477 keyword arguments. 

478 

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

480 C{class} or C{type}. 

481 

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

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

484 ''' 

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

486 other0 = other[0] 

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

488 isinstance(self, other0.__class__): 

489 return other0 

490 

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

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

493 isinstance(other, self.__class__): 

494 return _xnamed(other, name) 

495 

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

497 

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

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

500 

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

502 

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

504 ''' 

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

506# if self.name: 

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

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

509 

510# def toRepr(self, **kwds) 

511# if kwds: 

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

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

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

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

516 

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

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

519 notOverloaded(self, **kwds) 

520 

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

522# if kwds: 

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

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

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

526# return s 

527 

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

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

530 ''' 

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

532 if setters: 

533 d = self.__dict__ 

534 # double-check that setters are Property_RO's 

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

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

537 d[n] = v 

538 else: 

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

540 u += len(setters) 

541 return u 

542 

543 

544class _NamedDict(ADict, _Named): 

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

546 access to the items. 

547 ''' 

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

549 if args: # args override kwds 

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

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

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

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

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

555 if n: 

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

557 ADict.__init__(self, kwds) 

558 

559 def __delattr__(self, name): 

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

561 ''' 

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

563 ADict.pop(name) 

564 elif name in (_name_, _name): 

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

566 _Named.rename(self, NN) 

567 else: 

568 ADict.__delattr__(self, name) 

569 

570 def __getattr__(self, name): 

571 '''Get an attribute or item by B{C{name}}. 

572 ''' 

573 try: 

574 return self[name] 

575 except KeyError: 

576 if name == _name_: 

577 return _Named.name.fget(self) 

578 raise _AttributeError(item=self._DOT_(name), txt=_doesn_t_exist_) 

579 

580 def __getitem__(self, key): 

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

582 ''' 

583 if key == _name_: 

584 raise KeyError(Fmt.SQUARE(self.classname, key)) 

585 return ADict.__getitem__(self, key) 

586 

587 def __setattr__(self, name, value): 

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

589 ''' 

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

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

592 else: 

593 ADict.__setattr__(self, name, value) 

594 

595 def __setitem__(self, key, value): 

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

597 ''' 

598 if key == _name_: 

599 raise KeyError(_EQUAL_(Fmt.SQUARE(self.classname, key), repr(value))) 

600 ADict.__setitem__(self, key, value) 

601 

602 def toRepr(self, **prec_fmt): # PYCHOK signature 

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

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

605 ''' 

606 return Fmt.PAREN(self.name, self._toT(_EQUAL_, **prec_fmt)) 

607 

608 def toStr(self, **prec_fmt): # PYCHOK signature 

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

610 function L{pygeodesy.fstr}. 

611 ''' 

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

613 

614 

615class _NamedEnum(_NamedDict): 

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

617 restricted to valid keys. 

618 ''' 

619 _item_Classes = () 

620 

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

622 '''New C{_NamedEnum}. 

623 

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

625 values (C{type}). 

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

627 ''' 

628 self._item_Classes = (Class,) + Classes 

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

630 if n and _xvalid(n, _OK=True): 

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

632 

633 def __getattr__(self, name): 

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

635 ''' 

636 try: 

637 return self[name] 

638 except KeyError: 

639 if name == _name_: 

640 return _NamedDict.name.fget(self) 

641 raise _AttributeError(item=self._DOT_(name), txt=_doesn_t_exist_) 

642 

643 def __repr__(self): 

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

645 ''' 

646 return self.toRepr() 

647 

648 def __str__(self): 

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

650 ''' 

651 return self.toStr() 

652 

653 def _assert(self, **kwds): 

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

655 ''' 

656 pypy = _isPyPy() 

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

658 if isinstance(v, _LazyNamedEnumItem): # property 

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

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

661 setattr(self.__class__, n, v) 

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

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

664 and self.find(v) == n 

665 else: 

666 raise _TypeError(v, name=n) 

667 

668 def find(self, item, dflt=None): 

669 '''Find a registered item. 

670 

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

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

673 

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

675 there is no such I{registered} B{C{item}}. 

676 ''' 

677 for k, v in self.items(): # or ADict.items(self) 

678 if v is item: 

679 return k 

680 return dflt 

681 

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

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

684 

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

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

687 

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

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

690 ''' 

691 # getattr needed to instantiate L{_LazyNamedEnumItem} 

692 return getattr(self, name, dflt) 

693 

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

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

696 

697 @kwarg all: Use C{True} to yield {all} items or C{False} 

698 for only the currently I{registered} ones. 

699 @kwarg asorted: If C{True}, yield the items sorted in 

700 I{alphabetical, case-insensitive} order. 

701 ''' 

702 if all: # instantiate any remaining L{_LazyNamedEnumItem} ... 

703 # ... and remove the L{_LazyNamedEnumItem} from the class 

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

705 if isinstance(p, _LazyNamedEnumItem)): 

706 _ = getattr(self, n) 

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

708 

709 def keys(self, **all_asorted): 

710 '''Yield the keys (C{str}) of all or only the I{registered} items, 

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

712 

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

714 ''' 

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

716 yield k 

717 

718 def popitem(self): 

719 '''Remove I{an, any} curretly I{registed} item. 

720 

721 @return: The removed item. 

722 ''' 

723 return self._zapitem(*ADict.pop(self)) 

724 

725 def register(self, item): 

726 '''Registed a new item. 

727 

728 @arg item: The item (any C{type}). 

729 

730 @return: The item name (C{str}). 

731 

732 @raise NameError: An B{C{item}} already registered with 

733 that name or the B{C{item}} has no, an 

734 empty or an invalid name. 

735 

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

737 ''' 

738 try: 

739 n = item.name 

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

741 raise ValueError 

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

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

744 if n in self: 

745 raise _NameError(self._DOT_(n), item, txt=_exists_) 

746 if not (self._item_Classes and isinstance(item, self._item_Classes)): 

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

748 self[n] = item 

749 

750 def unregister(self, name_or_item): 

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

752 

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

754 

755 @return: The unregistered item. 

756 

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

758 

759 @raise ValueError: No such item. 

760 ''' 

761 if isstr(name_or_item): 

762 name = name_or_item 

763 else: 

764 name = self.find(name_or_item) 

765 try: 

766 item = ADict.pop(self, name) 

767 except KeyError: 

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

769 return self._zapitem(name, item) 

770 

771 pop = unregister 

772 

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

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

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

776 ''' 

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

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

779 

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

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

782 ''' 

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

784 

785 def values(self, **all_asorted): 

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

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

788 

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

790 ''' 

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

792 yield v 

793 

794 def _zapitem(self, name, item): 

795 # remove _LazyNamedEnumItem property value if still present 

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

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

798 item._enum = None 

799 return item 

800 

801 

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

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

804 ''' 

805 pass 

806 

807 

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

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

810 

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

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

813 ''' 

814 def _fget(inst): 

815 # assert isinstance(inst, _NamedEnum) 

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

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

818 item = inst[name] 

819 except KeyError: 

820 # instantiate an _NamedEnumItem, it self-registers 

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

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

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

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

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

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

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

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

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

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

831 if isinstance(p, _LazyNamedEnumItem): 

832 delattr(inst.__class__, name) 

833 # assert isinstance(item, _NamedEnumItem) 

834 return item 

835 

836 p = _LazyNamedEnumItem(_fget) 

837 p.name = name 

838 return p 

839 

840 

841class _NamedEnumItem(_NamedBase): 

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

843 ''' 

844 _enum = None 

845 

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

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

848# 

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

850# ''' 

851# return not self.__eq__(other) 

852 

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

854 def name(self): 

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

856 ''' 

857 return self._name 

858 

859 @name.setter # PYCHOK setter! 

860 def name(self, name): 

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

862 ''' 

863 if self._enum: 

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

865 self._name = str(name) 

866 

867 def _register(self, enum, name): 

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

869 

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

871 start with a letter. 

872 ''' 

873 if name and _xvalid(name, _OK=True): 

874 self.name = name 

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

876 enum.register(self) 

877 self._enum = enum 

878 

879 def unregister(self): 

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

881 

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

883 

884 @raise NameError: This item is unregistered. 

885 ''' 

886 enum = self._enum 

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

888 item = enum.unregister(self.name) 

889 if item is not self: 

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

891 raise _AssertionError(t) 

892 

893 

894class _NamedTuple(tuple, _Named): 

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

896 attribute name access to the items. 

897 

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

899 but statically defined, lighter and limited. 

900 ''' 

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

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

903 

904 @note: Specify at least 2 item names. 

905 ''' 

906 _Units_ = () # .units classes 

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

908 

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

910 ''' 

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

912 

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

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

915 

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

917 item of several more in other positional arguments. 

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

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

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

921 I{silently} ignored. 

922 

923 @raise LenError: Unequal number of positional arguments and 

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

925 

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

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

928 

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

930 or starts with C{underscore}. 

931 ''' 

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

933 self = tuple.__new__(cls, args) 

934 if not self._validated: 

935 self._validate() 

936 

937 N = len(self._Names_) 

938 if n != N: 

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

940 

941 if iteration_name: 

942 self._kwdself(**iteration_name) 

943 return self 

944 

945 def __delattr__(self, name): 

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

947 

948 @note: Items can not be deleted. 

949 ''' 

950 if name in self._Names_: 

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

952 elif name in (_name_, _name): 

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

954 else: 

955 tuple.__delattr__(self, name) 

956 

957 def __getattr__(self, name): 

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

959 ''' 

960 try: 

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

962 except IndexError: 

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

964 except ValueError: # e.g. _iteration 

965 return tuple.__getattribute__(self, name) 

966 

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

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

969# ''' 

970# return tuple.__getitem__(self, index) 

971 

972 def __hash__(self): 

973 return tuple.__hash__(self) 

974 

975 def __repr__(self): 

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

977 ''' 

978 return self.toRepr() 

979 

980 def __setattr__(self, name, value): 

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

982 ''' 

983 if name in self._Names_: 

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

985 elif name in (_name_, _name): 

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

987 else: # e.g. _iteration 

988 tuple.__setattr__(self, name, value) 

989 

990 def __str__(self): 

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

992 ''' 

993 return self.toStr() 

994 

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

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

997 

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

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

1000 

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

1002 

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

1004 ''' 

1005 tl = list(self) 

1006 if items: 

1007 _ix = self._Names_.index 

1008 try: 

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

1010 tl[_ix(n)] = v 

1011 except ValueError: # bad item name 

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

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

1014 

1015 def items(self): 

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

1017 

1018 @see: Method C{.units}. 

1019 ''' 

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

1021 yield n, v 

1022 

1023 iteritems = items 

1024 

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

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

1027 ''' 

1028 if iteration is not None: 

1029 self._iteration = iteration 

1030 if name: 

1031 self.name = name 

1032 

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

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

1035 

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

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

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

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

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

1041 

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

1043 ''' 

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

1045# if self.name: 

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

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

1048 

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

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

1051 

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

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

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

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

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

1057 

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

1059 ''' 

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

1061 

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

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

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

1065 

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

1067 

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

1069 

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

1071 ''' 

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

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

1074 

1075 def units(self, Error=UnitError): 

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

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

1078 

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

1080 

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

1082 

1083 @see: Method C{.items}. 

1084 ''' 

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

1086 if not (v is None or U is None 

1087 or (isclass(U) and 

1088 isinstance(v, U) and 

1089 hasattr(v, _name_) and 

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

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

1092 yield n, v 

1093 

1094 iterunits = units 

1095 

1096 def _validate(self, _OK=False): # see .EcefMatrix 

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

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

1099 ''' 

1100 ns = self._Names_ 

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

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

1103 for i, n in enumerate(ns): 

1104 if not _xvalid(n, _OK=_OK): 

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

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

1107 

1108 us = self._Units_ 

1109 if not isinstance(us, tuple): 

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

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

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

1113 for i, u in enumerate(us): 

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

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

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

1117 

1118 self.__class__._validated = True 

1119 

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

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

1122 ''' 

1123 if (issubclassof(xTuple, _NamedTuple) and 

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

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

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

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

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

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

1130 

1131 

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

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

1134 

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

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

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

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

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

1140 

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

1142 ''' 

1143 try: # see .lazily._caller3 

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

1145 n, f, s = _caller3(u) 

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

1147 not n.startswith(_UNDER_)): 

1148 if source: 

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

1150 return n 

1151 except (AttributeError, ValueError): 

1152 pass 

1153 return dflt 

1154 

1155 

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

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

1158 ''' 

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

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

1161 return n, kwds 

1162 

1163 

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

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

1166 ''' 

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

1168 if c: 

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

1170 if self_name: 

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

1172 return n 

1173 

1174 

1175def classname(inst, prefixed=None): 

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

1177 module name. 

1178 

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

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

1181 function C{classnaming}. 

1182 

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

1184 ''' 

1185 if prefixed is None: 

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

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

1188 

1189 

1190def classnaming(prefixed=None): 

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

1192 

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

1194 

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

1196 ''' 

1197 t = _Named._classnaming 

1198 if prefixed in (True, False): 

1199 _Named._classnaming = prefixed 

1200 return t 

1201 

1202 

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

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

1205 module name. 

1206 

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

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

1209 function C{classnaming}. 

1210 

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

1212 ''' 

1213 try: 

1214 n = clas.__name__ 

1215 except AttributeError: 

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

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

1218 try: 

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

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

1221 except AttributeError: 

1222 pass 

1223 return n 

1224 

1225 

1226def nameof(inst): 

1227 '''Get the name of an instance. 

1228 

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

1230 

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

1232 ''' 

1233 n = _xattr(inst, name=NN) 

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

1235 try: 

1236 n = inst.fget.__name__ 

1237 except AttributeError: 

1238 n = NN 

1239 return n 

1240 

1241 

1242def _notDecaps(where): 

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

1244 ''' 

1245 n = where.__name__ 

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

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

1248 

1249 

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

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

1252 ''' 

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

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

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

1256 

1257 

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

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

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

1261 ''' 

1262 if _std_NotImplemented: 

1263 return NotImplemented 

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

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

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

1267 

1268 

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

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

1271 property or for a missing caller feature. 

1272 

1273 @arg inst: Instance (C{any}) or C{None} for caller. 

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

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

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

1277 C{B{up}=2}. 

1278 ''' 

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

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

1281 raise _NotImplementedError(t, txt=_notDecaps(notImplemented)) 

1282 

1283 

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

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

1286 

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

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

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

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

1291 C{B{up}=2}. 

1292 ''' 

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

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

1295 raise _AssertionError(t, txt=_notDecaps(notOverloaded)) 

1296 

1297 

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

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

1300 ''' 

1301 return arg 

1302 

1303 

1304__all__ += _ALL_DOCS(_Named, 

1305 _NamedBase, # _NamedDict, 

1306 _NamedEnum, _NamedEnumItem, 

1307 _NamedTuple) 

1308 

1309# **) MIT License 

1310# 

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

1312# 

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

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

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

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

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

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

1319# 

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

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

1322# 

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

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

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

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

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

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

1329# OTHER DEALINGS IN THE SOFTWARE.