1

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

3

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

5

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

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

8

9 The items in a C{_NamedDict} are accessable as attributes and the items

10 in a C{_NamedTuple} are named to be accessable as attributes, similar to

11 standard Python C{namedtuple}s.

12

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

14'''

15

16 from pygeodesy.basics import isidentifier, iskeyword, isstr, itemsorted, len2, \

17 _xcopy, _xdup, _xinstanceof, _xsubclassof, _zip

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

19 _IndexError, _KeyError, LenError, _NameError, \

20 _NotImplementedError, _TypeError, _TypesError, \

21 _UnexpectedError, UnitError, _ValueError, \

22 _xattr, _xkwds, _xkwds_item2, _xkwds_pop2

23 from pygeodesy.internals import _caller3, _DUNDER_nameof, _getPYGEODESY, _isPyPy, \

24 _sizeof, _under

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

26 _COMMASPACE_, _doesn_t_exist_, _DOT_, _DUNDER_, \

27 _DUNDER_name_, _EQUAL_, _exists_, _immutable_, _name_, \

28 _NL_, _NN_, _no_, _other_, _s_, _SPACE_, _std_, \

29 _UNDER_, _vs_

30 from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS

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

32 _update_all, property_doc_, Property_RO, property_RO, \

33 _update_attrs

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

35# from pygeodesy.units import _toUnit # _MODS

36

37__all__ = _ALL_LAZY.named

38__version__ = '24.10.14'

39

40_COMMANL_ = _COMMA_ + _NL_

41_COMMASPACEDOT_ = _COMMASPACE_ + _DOT_

42_del_ = 'del'

43_item_ = 'item'

44_MRO_ = 'MRO'

45# __DUNDER gets mangled in class

46_name = _under(_name_)

47_Names_ = '_Names_'

48_registered_ = 'registered' # PYCHOK used!

49_std_NotImplemented = _getPYGEODESY('NOTIMPLEMENTED', NN).lower() == _std_

50_such_ = 'such'

51_Units_ = '_Units_'

52_UP = 2

53

54

55 class ADict(dict):

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

57 the C{dict} items.

58 '''

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

60

61 def __getattr__(self, name):

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

63 '''

64 try:

65 return self[name]

66 except KeyError:

67 if name == _name_:

68 return NN

69 raise self._AttributeError(name)

70

71 def __repr__(self):

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

73 '''

74 return self.toRepr()

75

76 def __setattr__(self, name, value):

77 '''Set the value of a I{known} item by B{C{name}}.

78 '''

79 try:

80 if self[name] != value:

81 self[name] = value

82 except KeyError:

83 dict.__setattr__(self, name, value)

84

85 def __str__(self):

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

87 '''

88 return self.toStr()

89

90 def _AttributeError(self, name):

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

92 '''

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

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

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

96

97 @property_RO

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

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

100 C{None} if not available/applicable.

101 '''

102 return self._iteration

103

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

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

106

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

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

109 '''

110 if iteration is not None:

111 self._iteration = iteration

112 if items:

113 dict.update(self, items)

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

115

116 def toRepr(self, **prec_fmt):

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

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

119 '''

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

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

122

123 def toStr(self, **prec_fmt):

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

125 function L{pygeodesy.fstr}.

126 '''

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

128

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

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

131 '''

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

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

134

135

136 class _Named(object):

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

138 '''

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

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

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

142# _updates = 0 # OBSOLETE Property/property updates

143

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

145 '''Not implemented.'''

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

147

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

149 '''Not implemented.'''

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

151

152 def __repr__(self):

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

154 '''

155 return Fmt.repr_at(self)

156

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

158 '''Not implemented.'''

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

160

161 def __str__(self):

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

163 '''

164 return self.named2

165

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

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

168 function L{pygeodesy.fstr}.

169

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

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

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

173 or C{None}-valued attributes.

174

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

176

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

178 '''

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

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

181

182 @Property_RO

183 def classname(self):

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

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

186 '''

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

188

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

190 def classnaming(self):

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

192 '''

193 return self._classnaming

194

195 @classnaming.setter # PYCHOK setter!

196 def classnaming(self, prefixed):

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

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

199 '''

200 b = bool(prefixed)

201 if self._classnaming != b:

202 self._classnaming = b

203 _update_attrs(self, *_Named_Property_ROs)

204

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

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

207

208 @arg args: Optional, positional arguments.

209 @kwarg kwds: Optional, keyword arguments.

210

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

212 '''

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

214

215 def copy(self, deep=False, **name):

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

217

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

219 copy (C{bool}).

220 @kwarg name: Optional, non-empty C{B{name}=NN} (C{str}).

221

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

223 '''

224 c = _xcopy(self, deep=deep)

225 if name:

226 _ = c.rename(name)

227 return c

228

229 def _DOT_(self, *names):

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

231 '''

232 return _DOT_(self.name, *names)

233

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

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

236

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

238 (C{bool}).

239 @kwarg items: Attributes to be changed (C{any}), including

240 optional C{B{name}} (C{str}).

241

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

243

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

245 '''

246 n = self.name

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

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

249 if m != n:

250 d.rename(m) # zap _Named_Property_ROs

251# if items:

252# _update_all(d)

253 return d

254

255 def _instr(self, *attrs, **fmt_prec_props_sep_name__kwds):

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

257 '''

258 def _fmt_prec_props_kwds(fmt=Fmt.F, prec=6, props=(), sep=_COMMASPACE_, **kwds):

259 return fmt, prec, props, sep, kwds

260

261 name, kwds = _name2__(**fmt_prec_props_sep_name__kwds)

262 fmt, prec, props, sep, kwds = _fmt_prec_props_kwds(**kwds)

263

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

265 if attrs:

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

267 prec=prec, ints=True, fmt=fmt)

268 if props:

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

270 prec=prec, ints=True)

271 if kwds:

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

273 return sep.join(t) if sep else t

274

275 @property_RO

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

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

278 if not available or not applicable.

279

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

281 several, nested functions.

282 '''

283 return self._iteration

284

285 def methodname(self, which):

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

287

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

289 '''

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

291

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

293 def name(self):

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

295 '''

296 return self._name

297

298 @name.setter # PYCHOK setter!

299 def name(self, name):

300 '''Set the C{B{name}=NN} (C{str}).

301

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

303 '''

304 m, n = self._name, _name__(name)

305 if not m:

306 self._name = n

307 elif n != m:

308 n = repr(n)

309 c = self.classname

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

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

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

313 n = _SPACE_(n, m)

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

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

316 # self.name = name or

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

318 # _Named(self).name = name

319

320 def _name__(self, name): # usually **name

321 '''(INTERNAL) Get the C{name} or this C{name}.

322 '''

323 return _name__(name, _or_nameof=self) # nameof(self)

324

325 def _name1__(self, kwds):

326 '''(INTERNAL) Resolve and set the C{B{name}=NN}.

327 '''

328 return _name1__(kwds, _or_nameof=self.name) if self.name else kwds

329

330 @Property_RO

331 def named(self):

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

333 '''

334 return self.name or self.classname

335

336# @Property_RO

337# def named_(self):

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

339# '''

340# return _xjoined_(self.classname, self.name, enquote=False)

341

342 @Property_RO

343 def named2(self):

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

345 '''

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

347

348 @Property_RO

349 def named3(self):

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

351 '''

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

353

354 @Property_RO

355 def named4(self):

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

357 '''

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

359

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

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

362 '''

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

364

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

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

367 '''

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

369

370 def rename(self, name):

371 '''Change the name.

372

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

374

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

376 '''

377 m, n = self._name, _name__(name)

378 if n != m:

379 self._name = n

380 _update_attrs(self, *_Named_Property_ROs)

381 return m

382

383 def renamed(self, name):

384 '''Change the name.

385

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

387

388 @return: This instance (C{str}).

389 '''

390 _ = self.rename(name)

391 return self

392

393 @property_RO

394 def sizeof(self):

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

396 '''

397 return _sizeof(self)

398

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

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

401 '''

402 return repr(self)

403

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

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

406 '''

407 return str(self)

408

409 @deprecated_method

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

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

412 return self.toRepr(**kwds)

413

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

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

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

417#

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

419# '''

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

421

422 def _xnamed(self, inst, name=NN, **force):

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

424

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

426 @kwarg name: The name (C{str}).

427 @kwarg force: If C{True}, force rename (C{bool}).

428

429 @return: The B{C{inst}}, renamed if B{C{force}}d

430 or if not named before.

431 '''

432 return _xnamed(inst, name, **force)

433

434 def _xrenamed(self, inst):

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

436

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

438

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

440

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

442 '''

443 _xinstanceof(_Named, inst=inst) # assert

444 return inst.renamed(self.name)

445

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

447

448

449 class _NamedBase(_Named):

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

451 '''

452 def __repr__(self):

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

454 '''

455 return self.toRepr()

456

457 def __str__(self):

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

459 '''

460 return self.toStr()

461

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

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

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

465

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

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

468 keyword arguments.

469

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

471 C{class} or C{type}.

472

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

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

475 '''

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

477 other0 = other[0]

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

479 isinstance(self, other0.__class__):

480 return other0

481

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

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

484 isinstance(other, self.__class__):

485 return _xnamed(other, name)

486

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

488

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

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

491

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

493

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

495 '''

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

497# if self.name:

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

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

500

501# def toRepr(self, **kwds)

502# if kwds:

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

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

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

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

507

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

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

510 notOverloaded(self, **kwds)

511

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

513# if kwds:

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

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

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

517# return s

518

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

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

521 '''

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

523 if setters:

524 d = self.__dict__

525 # double-check that setters are Property_RO's

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

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

528 d[n] = v

529 else:

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

531 u += len(setters)

532 return u

533

534

535 class _NamedDict(ADict, _Named):

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

537 to the items.

538 '''

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

540 if args: # is args[0] a dict?

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

542 kwds = _name1__(kwds)

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

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

545 kwds = _xkwds(dict(args[0]), **kwds) # args[0] overrides kwds

546 n, kwds = _name2__(**kwds)

547 if n:

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

549 ADict.__init__(self, kwds)

550

551 def __delattr__(self, name):

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

553 '''

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

555 ADict.pop(self, name)

556 elif name in (_name_, _name):

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

558 _Named.rename(self, NN)

559 else:

560 ADict.__delattr__(self, name)

561

562 def __getattr__(self, name):

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

564 '''

565 try:

566 return self[name]

567 except KeyError:

568 if name == _name_:

569 return _Named.name.fget(self)

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

571

572 def __getitem__(self, key):

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

574 '''

575 if key == _name_:

576 raise self._KeyError(key)

577 return ADict.__getitem__(self, key)

578

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

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

581 '''

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

583 t = Fmt.SQUARE(n, key)

584 if value:

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

586 return _KeyError(t)

587

588 def __setattr__(self, name, value):

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

590 '''

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

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

593 else:

594 ADict.__setattr__(self, name, value)

595

596 def __setitem__(self, key, value):

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

598 '''

599 if key == _name_:

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

601 ADict.__setitem__(self, key, value)

602

603

604 class _NamedEnum(_NamedDict):

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

606 restricted to valid keys.

607 '''

608 _item_Classes = ()

609

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

611 '''New C{_NamedEnum}.

612

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

614 values (C{type}).

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

616 '''

617 self._item_Classes = (Class,) + Classes

618 n = _name__(**name) or NN(Class.__name__, _s_) # _DUNDER_nameof

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

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

621

622 def __getattr__(self, name):

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

624 '''

625 return _NamedDict.__getattr__(self, name)

626

627 def __repr__(self):

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

629 '''

630 return self.toRepr()

631

632 def __str__(self):

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

634 '''

635 return self.toStr()

636

637 def _assert(self, **kwds):

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

639 '''

640 pypy = _isPyPy()

641 _isa = isinstance

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

643 if _isa(v, _LazyNamedEnumItem): # property

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

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

646 setattr(self.__class__, n, v)

647 elif _isa(v, self._item_Classes): # PYCHOK no cover

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

649 and self.find(v) == n

650 else:

651 raise _TypeError(v, name=n)

652

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

654 '''Find a registered item.

655

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

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

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

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

660

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

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

663 '''

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

665 if v is item:

666 return k

667 return dflt

668

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

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

671

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

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

674

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

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

677 '''

678 # getattr needed to instantiate L{_LazyNamedEnumItem}

679 return getattr(self, name, dflt)

680

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

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

683

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

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

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

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

688 '''

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

690 _isa = isinstance

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

692 if _isa(p, _LazyNamedEnumItem):

693 _ = getattr(self, n)

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

695

696 def keys(self, **all_asorted):

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

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

699

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

701 '''

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

703 yield k

704

705 def popitem(self):

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

707

708 @return: The removed item.

709 '''

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

711

712 def register(self, item):

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

714

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

716

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

718

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

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

721 invalid name.

722

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

724 '''

725 if item is all or item is any:

726 _ = self.items(all=True)

727 n = item.__name__

728 else:

729 try:

730 n = item.name

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

732 raise ValueError()

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

734 n = _DOT_(_item_, _name_)

735 raise _NameError(n, item, cause=x)

736 if n in self:

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

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

739 if not isinstance(item, self._item_Classes): # _xinstanceof

740 n = self._DOT_(n)

741 raise _TypesError(n, item, *self._item_Classes)

742 self[n] = item

743 return n

744

745 def unregister(self, name_or_item):

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

747

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

749

750 @return: The unregistered item.

751

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

753

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

755 '''

756 if isstr(name_or_item):

757 name = name_or_item

758 else:

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

760 if name is MISSING:

761 t = _SPACE_(_no_, _such_, self.classname, _item_)

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

763 try:

764 item = ADict.pop(self, name)

765 except KeyError:

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

767 return self._zapitem(name, item)

768

769 pop = unregister

770

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

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

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

774 '''

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

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

777

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

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

780 '''

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

782

783 def values(self, **all_asorted):

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

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

786

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

788 '''

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

790 yield v

791

792 def _zapitem(self, name, item):

793 # remove _LazyNamedEnumItem property value if still present

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

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

796 item._enum = None

797 return item

798

799

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

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

802 '''

803 pass

804

805

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

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

808

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

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

811 '''

812 def _fget(inst):

813 # assert isinstance(inst, _NamedEnum)

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

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

816 item = inst[name]

817 except KeyError:

818 # instantiate an _NamedEnumItem, it self-registers

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

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

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

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

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

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

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

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

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

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

829 if isinstance(p, _LazyNamedEnumItem):

830 delattr(inst.__class__, name)

831 # assert isinstance(item, _NamedEnumItem)

832 return item

833

834 p = _LazyNamedEnumItem(_fget)

835 p.name = name

836 return p

837

838

839 class _NamedEnumItem(_NamedBase):

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

841 '''

842 _enum = None

843

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

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

846#

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

848# '''

849# return not self.__eq__(other)

850

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

852 def name(self):

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

854 '''

855 return self._name

856

857 @name.setter # PYCHOK setter!

858 def name(self, name):

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

860 '''

861 name = _name__(name) or _NN_

862 if self._enum:

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

864 if name:

865 self._name = 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 name = _name__(name)

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

875 self.name = name

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

877 enum.register(self)

878 self._enum = enum

879

880 def unregister(self):

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

882

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

884

885 @raise NameError: This item is unregistered.

886 '''

887 enum = self._enum

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

889 item = enum.unregister(self.name)

890 if item is not self: # PYCHOK no cover

891 t = _SPACE_(repr(item), _vs_, repr(self))

892 raise _AssertionError(t)

893

894

895# from pygeodesy.props import _NamedProperty

896

897

898 class _NamedTuple(tuple, _Named):

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

900 attribute name access to the items.

901

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

903 but statically defined, lighter and limited.

904 '''

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

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

907

908 @note: Specify at least 2 item names.

909 '''

910 _Units_ = () # .units classes

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

912

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

914 '''

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

916

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

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

919

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

921 item of several more in other positional arguments.

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

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

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

925 I{silently} ignored.

926

927 @raise LenError: Unequal number of positional arguments and

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

929

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

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

932

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

934 or starts with C{underscore}.

935 '''

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

937 self = tuple.__new__(cls, args)

938 if not self._validated:

939 self._validate()

940

941 N = len(self._Names_)

942 if n != N:

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

944

945 if iteration_name:

946 i, name = _xkwds_pop2(iteration_name, iteration=None)

947 if i is not None:

948 self._iteration = i

949 if name:

950 self.name = name

951 return self

952

953 def __delattr__(self, name):

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

955

956 @note: Items can not be deleted.

957 '''

958 if name in self._Names_:

959 t = _SPACE_(_del_, self._DOT_(name))

960 raise _TypeError(t, txt=_immutable_)

961 elif name in (_name_, _name):

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

963 else:

964 tuple.__delattr__(self, name)

965

966 def __getattr__(self, name):

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

968 '''

969 try:

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

971 except IndexError as x:

972 raise _IndexError(self._DOT_(name), cause=x)

973 except ValueError: # e.g. _iteration

974 return tuple.__getattr__(self, name) # __getattribute__

975

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

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

978# '''

979# return tuple.__getitem__(self, index)

980

981 def __hash__(self):

982 return tuple.__hash__(self)

983

984 def __repr__(self):

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

986 '''

987 return self.toRepr()

988

989 def __setattr__(self, name, value):

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

991 '''

992 if name in self._Names_:

993 t = Fmt.EQUALSPACED(self._DOT_(name), repr(value))

994 raise _TypeError(t, txt=_immutable_)

995 elif name in (_name_, _name):

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

997 else: # e.g. _iteration

998 tuple.__setattr__(self, name, value)

999

1000 def __str__(self):

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

1002 '''

1003 return self.toStr()

1004

1005 def _DOT_(self, *names):

1006 '''(INTERNAL) Period-join C{self.classname} and C{names}.

1007 '''

1008 return _DOT_(self.classname, *names)

1009

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

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

1012

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

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

1015

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

1017

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

1019 '''

1020 t = list(self)

1021 U = self._Units_

1022 if items:

1023 _ix = self._Names_.index

1024 _2U = _MODS.units._toUnit

1025 try:

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

1027 i = _ix(n)

1028 t[i] = _2U(U[i], v, name=n)

1029 except ValueError: # bad item name

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

1031 return self.classof(*t).reUnit(*U, name=name)

1032

1033 def items(self):

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

1035

1036 @see: Method C{.units}.

1037 '''

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

1039 yield n, v

1040

1041 iteritems = items

1042

1043 def reUnit(self, *Units, **name):

1044 '''Replace some of this C{Named-Tuple}'s C{Units}.

1045

1046 @arg Units: One or more C{Unit} classes, all positional.

1047 @kwarg name: Optional C{B{name}=NN} (C{str}).

1048

1049 @return: This instance with updated C{Units}.

1050

1051 @note: This C{Named-Tuple}'s values are I{not updated}.

1052 '''

1053 U = self._Units_

1054 n = min(len(U), len(Units))

1055 if n:

1056 R = Units + U[n:]

1057 if R != U:

1058 self._Units_ = R

1059 return self.renamed(name) if name else self

1060

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

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

1063

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

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

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

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

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

1069

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

1071 '''

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

1073# if self.name:

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

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

1076

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

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

1079

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

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

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

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

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

1085

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

1087 '''

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

1089

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

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

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

1093

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

1095 @kwarg name: Optional C{B{name}=NN} (C{str}).

1096

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

1098

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

1100 '''

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

1102 return self.classof(*t).reUnit(*self._Units_, **name)

1103

1104 def units(self, **Error):

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

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

1107

1108 @kwarg Error: Optional C{B{Error}=UnitError} to raise.

1109

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

1111

1112 @see: Method C{.items}.

1113 '''

1114 _2U = _MODS.units._toUnit

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

1116 yield n, _2U(U, v, name=n, **Error)

1117

1118 iterunits = units

1119

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

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

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

1123 '''

1124 ns = self._Names_

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

1126 raise _TypeError(self._DOT_(_Names_), ns)

1127 for i, n in enumerate(ns):

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

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

1130 raise _ValueError(self._DOT_(t), n)

1131

1132 us = self._Units_

1133 if not isinstance(us, tuple):

1134 raise _TypeError(self._DOT_(_Units_), us)

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

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

1137 for i, u in enumerate(us):

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

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

1140 raise _TypeError(self._DOT_(t), u)

1141

1142 self.__class__._validated = True

1143

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

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

1146 '''

1147 _xsubclassof(_NamedTuple, xTuple=xTuple)

1148 if len(xTuple._Names_) != (len(self._Names_) + len(items)) or \

1149 xTuple._Names_[:len(self)] != self._Names_: # PYCHOK no cover

1150 c = NN(self.classname, repr(self._Names_))

1151 x = NN(xTuple.__name__, repr(xTuple._Names_))

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

1153 t = self + items

1154 return xTuple(t, name=self._name__(name)) # .reUnit(*self._Units_)

1155

1156

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

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

1159

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

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

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

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

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

1165

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

1167 '''

1168 try: # see .lazily._caller3

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

1170 n, f, s = _caller3(u)

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

1172 not n.startswith(_UNDER_)):

1173 if source:

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

1175 return n

1176 except (AttributeError, ValueError):

1177 pass

1178 return dflt

1179

1180

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

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

1183 '''

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

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

1186 return n, kwds

1187

1188

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

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

1191 '''

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

1193 if c:

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

1195 if self_name:

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

1197 return n

1198

1199

1200 def classname(inst, prefixed=None):

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

1202 module name.

1203

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

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

1206 function C{classnaming}.

1207

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

1209 '''

1210 if prefixed is None:

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

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

1213

1214

1215 def classnaming(prefixed=None):

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

1217

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

1219

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

1221 '''

1222 t = _Named._classnaming

1223 if prefixed in (True, False):

1224 _Named._classnaming = prefixed

1225 return t

1226

1227

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

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

1230 module name.

1231

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

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

1234 function C{classnaming}.

1235

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

1237 '''

1238 try:

1239 n = clas.__name__

1240 except AttributeError:

1241 n = clas if isstr(clas) else _DUNDER_name_

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

1243 try:

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

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

1246 except AttributeError:

1247 pass

1248 return n

1249

1250

1251# def _name__(name=NN, name__=None, _or_nameof=None, **kwds):

1252# '''(INTERNAL) Get single keyword argument C{B{name}=NN|None}.

1253# '''

1254# if kwds: # "unexpected keyword arguments ..."

1255# m = _MODS.errors

1256# raise m._UnexpectedError(**kwds)

1257# if name: # is given

1258# n = _name__(**name) if isinstance(name, dict) else str(name)

1259# elif name__ is not None:

1260# n = getattr(name__, _DUNDER_name_, NN) # _xattr(name__, __name__=NN)

1261# else:

1262# n = name # NN or None or {} or any False type

1263# if _or_nameof is not None and not n:

1264# n = getattr(_or_nameof, _name_, NN) # _xattr(_or_nameof, name=NN)

1265# return n # str or None or {}

1266

1267

1268 def _name__(name=NN, **kwds):

1269 '''(INTERNAL) Get single keyword argument C{B{name}=NN|None}.

1270 '''

1271 if name or kwds:

1272 name, kwds = _name2__(name, **kwds)

1273 if kwds: # "unexpected keyword arguments ..."

1274 raise _UnexpectedError(**kwds)

1275 return name if name or name is None else NN

1276

1277

1278 def _name1__(kwds_name, **name__or_nameof):

1279 '''(INTERNAL) Resolve and set the C{B{name}=NN}.

1280 '''

1281 if kwds_name or name__or_nameof:

1282 n, kwds_name = _name2__(kwds_name, **name__or_nameof)

1283 kwds_name.update(name=n)

1284 return kwds_name

1285

1286

1287 def _name2__(name=NN, name__=None, _or_nameof=None, **kwds):

1288 '''(INTERNAL) Get the C{B{name}=NN|None} and other C{kwds}.

1289 '''

1290 if name: # is given

1291 if isinstance(name, dict):

1292 kwds.update(name) # kwds = _xkwds(kwds, **name)?

1293 n, kwds = _name2__(**kwds)

1294 else:

1295 n = str(name)

1296 elif name__ is not None:

1297 n = _DUNDER_nameof(name__, NN)

1298 else:

1299 n = name if name is None else NN

1300 if _or_nameof is not None and not n:

1301 n = _xattr(_or_nameof, name=NN) # nameof

1302 return n, kwds # (str or None or {}), dict

1303

1304

1305 def nameof(inst):

1306 '''Get the name of an instance.

1307

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

1309

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

1311 '''

1312 n = _xattr(inst, name=NN)

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

1314 try:

1315 n = inst.fget.__name__

1316 except AttributeError:

1317 n = NN

1318 return n

1319

1320

1321 def _notDecap(where):

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

1323 '''

1324 n = where.__name__

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

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

1327

1328

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

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

1331 '''

1332 n = _DOT_(classname(inst, prefixed=True), _DUNDER_nameof(name, name))

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

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

1335

1336

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

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

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

1340 '''

1341 if _std_NotImplemented:

1342 return NotImplemented

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

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

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

1346

1347

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

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

1350 property or for a missing caller feature.

1351

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

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

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

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

1356 C{B{up}=2}.

1357 '''

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

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

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

1361

1362

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

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

1365

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

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

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

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

1370 C{B{up}=2}.

1371 '''

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

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

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

1375

1376

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

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

1379 '''

1380 return arg

1381

1382

1383 def _xjoined_(prefix, name=NN, enquote=True, **name__or_nameof):

1384 '''(INTERNAL) Join C{prefix} and non-empty C{name}.

1385 '''

1386 if name__or_nameof:

1387 name = _name__(name, **name__or_nameof)

1388 if name and prefix:

1389 if enquote:

1390 name = repr(name)

1391 t = _SPACE_(prefix, name)

1392 else:

1393 t = prefix or name

1394 return t

1395

1396

1397 def _xnamed(inst, name=NN, force=False, **name__or_nameof):

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

1399

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

1401 @kwarg name: The name (C{str}).

1402 @kwarg force: If C{True}, force rename (C{bool}).

1403

1404 @return: The B{C{inst}}, renamed if B{C{force}}d

1405 or if not named before.

1406 '''

1407 if name__or_nameof:

1408 name = _name__(name, **name__or_nameof)

1409 if name and isinstance(inst, _Named):

1410 if not inst.name:

1411 inst.name = name

1412 elif force:

1413 inst.rename(name)

1414 return inst

1415

1416

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

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

1419 '''

1420 if name_other: # and other is None

1421 name, other = _xkwds_item2(name_other)

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

1423 name, other = _name__(name), other[0]

1424 else:

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

1426 return other, name, up

1427

1428

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

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

1431 '''

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

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

1434

1435

1436 def _xvalid(name, underOK=False):

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

1438 '''

1439 return bool(name and isstr(name)

1440 and name != _name_

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

1442 and (not iskeyword(name))

1443 and isidentifier(name))

1444

1445

1446__all__ += _ALL_DOCS(_Named,

1447 _NamedBase, # _NamedDict,

1448 _NamedEnum, _NamedEnumItem,

1449 _NamedTuple)

1450

1451# **) MIT License

1452#

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

1454#

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

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

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

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

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

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

1461#

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

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

1464#

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

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

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

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

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

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

1471# OTHER DEALINGS IN THE SOFTWARE.