Coverage for pygeodesy/named.py: 96%

451 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-02-12 13:15 -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 len2, _sizeof, _xcopy, _xdup, _zip 

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

19 _IndexError, _IsnotError, itemsorted, LenError, \ 

20 _NameError, _NotImplementedError, _TypeError, \ 

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

22 _xkwds_get, _xkwds_pop, _xkwds_popitem 

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

24 _COMMASPACE_, _doesn_t_exist_, _DOT_, _DUNDER_, \ 

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

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

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

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

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

30 _update_all, property_doc_, Property_RO, property_RO, \ 

31 _update_attrs 

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

33 

34__all__ = _ALL_LAZY.named 

35__version__ = '24.02.04' 

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_popitem(name_other) 

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

80 other = other[0] 

81 else: 

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

83 return other, name, up 

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} or sub-class thereof). 

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} or sub-class thereof). 

276 

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

278 ''' 

279 n = self.name 

280 m = _xkwds_pop(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 old 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: 

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 if _name_ in kwds: 

555 _Named.name.fset(self, kwds.pop(_name_)) # see _Named.name 

556 ADict.__init__(self, kwds) 

557 

558 def __delattr__(self, name): 

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

560 ''' 

561 if name in ADict.keys(self): 

562 ADict.pop(name) 

563 elif name in (_name_, _name): 

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

565 _Named.rename(self, NN) 

566 else: 

567 ADict.__delattr__(self, name) 

568 

569 def __getattr__(self, name): 

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

571 ''' 

572 try: 

573 return self[name] 

574 except KeyError: 

575 if name == _name_: 

576 return _Named.name.fget(self) 

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

578 

579 def __getitem__(self, key): 

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

581 ''' 

582 if key == _name_: 

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

584 return ADict.__getitem__(self, key) 

585 

586 def __setattr__(self, name, value): 

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

588 ''' 

589 if name in ADict.keys(self): 

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

591 else: 

592 ADict.__setattr__(self, name, value) 

593 

594 def __setitem__(self, key, value): 

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

596 ''' 

597 if key == _name_: 

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

599 ADict.__setitem__(self, key, value) 

600 

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

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

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

604 ''' 

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

606 

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

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

609 function L{pygeodesy.fstr}. 

610 ''' 

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

612 

613 

614class _NamedEnum(_NamedDict): 

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

616 restricted to valid keys. 

617 ''' 

618 _item_Classes = () 

619 

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

621 '''New C{_NamedEnum}. 

622 

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

624 values (C{type}). 

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

626 ''' 

627 self._item_Classes = (Class,) + Classes 

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

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

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

631 

632 def __getattr__(self, name): 

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

634 ''' 

635 try: 

636 return self[name] 

637 except KeyError: 

638 if name == _name_: 

639 return _NamedDict.name.fget(self) 

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

641 

642 def __repr__(self): 

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

644 ''' 

645 return self.toRepr() 

646 

647 def __str__(self): 

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

649 ''' 

650 return self.toStr() 

651 

652 def _assert(self, **kwds): 

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

654 ''' 

655 pypy = _isPyPy() 

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

657 if isinstance(v, _LazyNamedEnumItem): # property 

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

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

660 setattr(self.__class__, n, v) 

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

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

663 and self.find(v) == n 

664 else: 

665 raise _TypeError(v, name=n) 

666 

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

668 '''Find a registered item. 

669 

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

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

672 

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

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

675 ''' 

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

677 if v is item: 

678 return k 

679 return dflt 

680 

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

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

683 

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

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

686 

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

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

689 ''' 

690 # getattr needed to instantiate L{_LazyNamedEnumItem} 

691 return getattr(self, name, dflt) 

692 

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

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

695 

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

697 for only the currently I{registered} ones. 

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

699 I{alphabetical, case-insensitive} order. 

700 ''' 

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

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

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

704 if isinstance(p, _LazyNamedEnumItem)): 

705 _ = getattr(self, n) 

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

707 

708 def keys(self, **all_asorted): 

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

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

711 

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

713 ''' 

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

715 yield k 

716 

717 def popitem(self): 

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

719 

720 @return: The removed item. 

721 ''' 

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

723 

724 def register(self, item): 

725 '''Registed a new item. 

726 

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

728 

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

730 

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

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

733 empty or an invalid name. 

734 

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

736 ''' 

737 try: 

738 n = item.name 

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

740 raise ValueError 

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

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

743 if n in self: 

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

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

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

747 self[n] = item 

748 

749 def unregister(self, name_or_item): 

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

751 

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

753 

754 @return: The unregistered item. 

755 

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

757 

758 @raise ValueError: No such item. 

759 ''' 

760 if isstr(name_or_item): 

761 name = name_or_item 

762 else: 

763 name = self.find(name_or_item) 

764 try: 

765 item = ADict.pop(self, name) 

766 except KeyError: 

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

768 return self._zapitem(name, item) 

769 

770 pop = unregister 

771 

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

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

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

775 ''' 

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

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

778 

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

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

781 ''' 

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

783 

784 def values(self, **all_asorted): 

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

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

787 

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

789 ''' 

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

791 yield v 

792 

793 def _zapitem(self, name, item): 

794 # remove _LazyNamedEnumItem property value if still present 

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

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

797 item._enum = None 

798 return item 

799 

800 

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

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

803 ''' 

804 pass 

805 

806 

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

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

809 

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

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

812 ''' 

813 def _fget(inst): 

814 # assert isinstance(inst, _NamedEnum) 

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

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

817 item = inst[name] 

818 except KeyError: 

819 # instantiate an _NamedEnumItem, it self-registers 

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

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

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

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

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

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

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

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

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

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

830 if isinstance(p, _LazyNamedEnumItem): 

831 delattr(inst.__class__, name) 

832 # assert isinstance(item, _NamedEnumItem) 

833 return item 

834 

835 p = _LazyNamedEnumItem(_fget) 

836 p.name = name 

837 return p 

838 

839 

840class _NamedEnumItem(_NamedBase): 

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

842 ''' 

843 _enum = None 

844 

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

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

847# 

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

849# ''' 

850# return not self.__eq__(other) 

851 

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

853 def name(self): 

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

855 ''' 

856 return self._name 

857 

858 @name.setter # PYCHOK setter! 

859 def name(self, name): 

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

861 ''' 

862 if self._enum: 

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

864 self._name = str(name) 

865 

866 def _register(self, enum, name): 

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

868 

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

870 start with a letter. 

871 ''' 

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

873 self.name = name 

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

875 enum.register(self) 

876 self._enum = enum 

877 

878 def unregister(self): 

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

880 

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

882 

883 @raise NameError: This item is unregistered. 

884 ''' 

885 enum = self._enum 

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

887 item = enum.unregister(self.name) 

888 if item is not self: 

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

890 raise _AssertionError(t) 

891 

892 

893class _NamedTuple(tuple, _Named): 

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

895 attribute name access to the items. 

896 

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

898 but statically defined, lighter and limited. 

899 ''' 

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

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

902 

903 @note: Specify at least 2 item names. 

904 ''' 

905 _Units_ = () # .units classes 

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

907 

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

909 ''' 

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

911 

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

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

914 

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

916 item of several more in other positional arguments. 

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

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

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

920 I{silently} ignored. 

921 

922 @raise LenError: Unequal number of positional arguments and 

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

924 

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

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

927 

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

929 or starts with C{underscore}. 

930 ''' 

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

932 self = tuple.__new__(cls, args) 

933 if not self._validated: 

934 self._validate() 

935 

936 N = len(self._Names_) 

937 if n != N: 

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

939 

940 if iteration_name: 

941 self._kwdself(**iteration_name) 

942 return self 

943 

944 def __delattr__(self, name): 

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

946 

947 @note: Items can not be deleted. 

948 ''' 

949 if name in self._Names_: 

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

951 elif name in (_name_, _name): 

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

953 else: 

954 tuple.__delattr__(self, name) 

955 

956 def __getattr__(self, name): 

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

958 ''' 

959 try: 

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

961 except IndexError: 

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

963 except ValueError: # e.g. _iteration 

964 return tuple.__getattribute__(self, name) 

965 

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

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

968# ''' 

969# return tuple.__getitem__(self, index) 

970 

971 def __repr__(self): 

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

973 ''' 

974 return self.toRepr() 

975 

976 def __setattr__(self, name, value): 

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

978 ''' 

979 if name in self._Names_: 

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

981 elif name in (_name_, _name): 

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

983 else: # e.g. _iteration 

984 tuple.__setattr__(self, name, value) 

985 

986 def __str__(self): 

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

988 ''' 

989 return self.toStr() 

990 

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

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

993 

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

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

996 

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

998 

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

1000 ''' 

1001 tl = list(self) 

1002 if items: 

1003 _ix = self._Names_.index 

1004 try: 

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

1006 tl[_ix(n)] = v 

1007 except ValueError: # bad item name 

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

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

1010 

1011 def items(self): 

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

1013 

1014 @see: Method C{.units}. 

1015 ''' 

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

1017 yield n, v 

1018 

1019 iteritems = items 

1020 

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

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

1023 ''' 

1024 if iteration is not None: 

1025 self._iteration = iteration 

1026 if name: 

1027 self.name = name 

1028 

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

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

1031 

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

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

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

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

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

1037 

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

1039 ''' 

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

1041# if self.name: 

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

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

1044 

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

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

1047 

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

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

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

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

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

1053 

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

1055 ''' 

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

1057 

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

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

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

1061 

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

1063 

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

1065 

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

1067 ''' 

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

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

1070 

1071 def units(self, Error=UnitError): 

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

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

1074 

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

1076 

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

1078 

1079 @see: Method C{.items}. 

1080 ''' 

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

1082 if not (v is None or U is None 

1083 or (isclass(U) and 

1084 isinstance(v, U) and 

1085 hasattr(v, _name_) and 

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

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

1088 yield n, v 

1089 

1090 iterunits = units 

1091 

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

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

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

1095 ''' 

1096 ns = self._Names_ 

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

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

1099 for i, n in enumerate(ns): 

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

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

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

1103 

1104 us = self._Units_ 

1105 if not isinstance(us, tuple): 

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

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

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

1109 for i, u in enumerate(us): 

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

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

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

1113 

1114 self.__class__._validated = True 

1115 

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

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

1118 ''' 

1119 if (issubclassof(xTuple, _NamedTuple) and 

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

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

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

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

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

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

1126 

1127 

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

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

1130 

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

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

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

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

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

1136 

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

1138 ''' 

1139 try: # see .lazily._caller3 

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

1141 n, f, s = _caller3(u) 

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

1143 not n.startswith(_UNDER_)): 

1144 if source: 

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

1146 return n 

1147 except (AttributeError, ValueError): 

1148 pass 

1149 return dflt 

1150 

1151 

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

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

1154 ''' 

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

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

1157 return n, kwds 

1158 

1159 

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

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

1162 ''' 

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

1164 if c: 

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

1166 if self_name: 

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

1168 return n 

1169 

1170 

1171def classname(inst, prefixed=None): 

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

1173 module name. 

1174 

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

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

1177 function C{classnaming}. 

1178 

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

1180 ''' 

1181 if prefixed is None: 

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

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

1184 

1185 

1186def classnaming(prefixed=None): 

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

1188 

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

1190 

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

1192 ''' 

1193 t = _Named._classnaming 

1194 if prefixed in (True, False): 

1195 _Named._classnaming = prefixed 

1196 return t 

1197 

1198 

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

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

1201 module name. 

1202 

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

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

1205 function C{classnaming}. 

1206 

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

1208 ''' 

1209 try: 

1210 n = clas.__name__ 

1211 except AttributeError: 

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

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

1214 try: 

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

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

1217 except AttributeError: 

1218 pass 

1219 return n 

1220 

1221 

1222def nameof(inst): 

1223 '''Get the name of an instance. 

1224 

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

1226 

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

1228 ''' 

1229 n = _xattr(inst, name=NN) 

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

1231 try: 

1232 n = inst.fget.__name__ 

1233 except AttributeError: 

1234 n = NN 

1235 return n 

1236 

1237 

1238def _notDecaps(where): 

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

1240 ''' 

1241 n = where.__name__ 

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

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

1244 

1245 

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

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

1248 ''' 

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

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

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

1252 

1253 

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

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

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

1257 ''' 

1258 if _std_NotImplemented: 

1259 return NotImplemented 

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

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

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

1263 

1264 

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

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

1267 property or for a missing caller feature. 

1268 

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

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

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

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

1273 C{B{up}=2}. 

1274 ''' 

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

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

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

1278 

1279 

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

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

1282 

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

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

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

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

1287 C{B{up}=2}. 

1288 ''' 

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

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

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

1292 

1293 

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

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

1296 ''' 

1297 return arg 

1298 

1299 

1300__all__ += _ALL_DOCS(_Named, 

1301 _NamedBase, # _NamedDict, 

1302 _NamedEnum, _NamedEnumItem, 

1303 _NamedTuple) 

1304 

1305# **) MIT License 

1306# 

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

1308# 

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

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

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

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

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

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

1315# 

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

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

1318# 

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

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

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

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

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

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

1325# OTHER DEALINGS IN THE SOFTWARE.