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, _isPyPy, _sizeof, _under

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

25 _COMMASPACE_, _doesn_t_exist_, _DOT_, _DUNDER_, \

26 _dunder_name_, _EQUAL_, _exists_, _immutable_, _name_, \

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

28 _UNDER_, _vs_

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

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

31 _update_all, property_doc_, Property_RO, property_RO, \

32 _update_attrs

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

34# from pygeodesy.units import _toUnit # _MODS

35

36__all__ = _ALL_LAZY.named

37__version__ = '24.08.13'

38

39_COMMANL_ = _COMMA_ + _NL_

40_COMMASPACEDOT_ = _COMMASPACE_ + _DOT_

41_del_ = 'del'

42_item_ = 'item'

43_MRO_ = 'MRO'

44# __DUNDER gets mangled in class

45_name = _under(_name_)

46_Names_ = '_Names_'

47_registered_ = 'registered' # PYCHOK used!

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

49_such_ = 'such'

50_Units_ = '_Units_'

51_UP = 2

52

53

54 class ADict(dict):

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

56 the C{dict} items.

57 '''

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

59

60 def __getattr__(self, name):

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

62 '''

63 try:

64 return self[name]

65 except KeyError:

66 if name == _name_:

67 return NN

68 raise self._AttributeError(name)

69

70 def __repr__(self):

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

72 '''

73 return self.toRepr()

74

75 def __setattr__(self, name, value):

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

77 '''

78 try:

79 if self[name] != value:

80 self[name] = value

81 except KeyError:

82 dict.__setattr__(self, name, value)

83

84 def __str__(self):

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

86 '''

87 return self.toStr()

88

89 def _AttributeError(self, name):

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

91 '''

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

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

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

95

96 @property_RO

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

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

99 C{None} if not available/applicable.

100 '''

101 return self._iteration

102

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

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

105

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

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

108 '''

109 if iteration is not None:

110 self._iteration = iteration

111 if items:

112 dict.update(self, items)

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

114

115 def toRepr(self, **prec_fmt):

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

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

118 '''

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

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

121

122 def toStr(self, **prec_fmt):

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

124 function L{pygeodesy.fstr}.

125 '''

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

127

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

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

130 '''

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

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

133

134

135 class _Named(object):

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

137 '''

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

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

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

141# _updates = 0 # OBSOLETE Property/property updates

142

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

144 '''Not implemented.'''

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

146

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

148 '''Not implemented.'''

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

150

151 def __repr__(self):

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

153 '''

154 return Fmt.repr_at(self)

155

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

157 '''Not implemented.'''

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

159

160 def __str__(self):

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

162 '''

163 return self.named2

164

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

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

167 function L{pygeodesy.fstr}.

168

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

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

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

172 or C{None}-valued attributes.

173

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

175

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

177 '''

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

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

180

181 @Property_RO

182 def classname(self):

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

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

185 '''

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

187

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

189 def classnaming(self):

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

191 '''

192 return self._classnaming

193

194 @classnaming.setter # PYCHOK setter!

195 def classnaming(self, prefixed):

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

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

198 '''

199 b = bool(prefixed)

200 if self._classnaming != b:

201 self._classnaming = b

202 _update_attrs(self, *_Named_Property_ROs)

203

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

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

206

207 @arg args: Optional, positional arguments.

208 @kwarg kwds: Optional, keyword arguments.

209

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

211 '''

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

213

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

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

216

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

218 copy (C{bool}).

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

220

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

222 '''

223 c = _xcopy(self, deep=deep)

224 if name:

225 _ = c.rename(name)

226 return c

227

228 def _DOT_(self, *names):

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

230 '''

231 return _DOT_(self.name, *names)

232

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

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

235

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

237 (C{bool}).

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

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

240

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

242

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

244 '''

245 n = self.name

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

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

248 if m != n:

249 d.rename(m) # zap _Named_Property_ROs

250# if items:

251# _update_all(d)

252 return d

253

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

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

256 '''

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

258 return fmt, prec, props, sep, kwds

259

260 name, kwds = _name2__(**fmt_prec_props_sep_name__kwds)

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

262

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

264 if attrs:

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

266 prec=prec, ints=True, fmt=fmt)

267 if props:

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

269 prec=prec, ints=True)

270 if kwds:

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

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

273

274 @property_RO

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

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

277 if not available or not applicable.

278

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

280 several, nested functions.

281 '''

282 return self._iteration

283

284 def methodname(self, which):

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

286

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

288 '''

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

290

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

292 def name(self):

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

294 '''

295 return self._name

296

297 @name.setter # PYCHOK setter!

298 def name(self, name):

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

300

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

302 '''

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

304 if not m:

305 self._name = n

306 elif n != m:

307 n = repr(n)

308 c = self.classname

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

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

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

312 n = _SPACE_(n, m)

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

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

315 # self.name = name or

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

317 # _Named(self).name = name

318

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

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

321 '''

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

323

324 def _name1__(self, kwds):

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

326 '''

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

328

329 @Property_RO

330 def named(self):

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

332 '''

333 return self.name or self.classname

334

335# @Property_RO

336# def named_(self):

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

338# '''

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

340

341 @Property_RO

342 def named2(self):

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

344 '''

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

346

347 @Property_RO

348 def named3(self):

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

350 '''

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

352

353 @Property_RO

354 def named4(self):

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

356 '''

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

358

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

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

361 '''

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

363

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

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

366 '''

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

368

369 def rename(self, name):

370 '''Change the name.

371

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

373

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

375 '''

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

377 if n != m:

378 self._name = n

379 _update_attrs(self, *_Named_Property_ROs)

380 return m

381

382 def renamed(self, name):

383 '''Change the name.

384

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

386

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

388 '''

389 _ = self.rename(name)

390 return self

391

392 @property_RO

393 def sizeof(self):

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

395 '''

396 return _sizeof(self)

397

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

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

400 '''

401 return repr(self)

402

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

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

405 '''

406 return str(self)

407

408 @deprecated_method

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

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

411 return self.toRepr(**kwds)

412

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

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

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

416#

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

418# '''

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

420

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

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

423

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

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

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

427

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

429 or if not named before.

430 '''

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

432

433 def _xrenamed(self, inst):

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

435

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

437

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

439

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

441 '''

442 _xinstanceof(_Named, inst=inst) # assert

443 return inst.renamed(self.name)

444

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

446

447

448 class _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 others(self, *other, **name_other_up):

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

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

464

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

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

467 keyword arguments.

468

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

470 C{class} or C{type}.

471

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

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

474 '''

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

476 other0 = other[0]

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

478 isinstance(self, other0.__class__):

479 return other0

480

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

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

483 isinstance(other, self.__class__):

484 return _xnamed(other, name)

485

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

487

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

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

490

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

492

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

494 '''

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

496# if self.name:

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

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

499

500# def toRepr(self, **kwds)

501# if kwds:

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

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

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

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

506

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

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

509 notOverloaded(self, **kwds)

510

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

512# if kwds:

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

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

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

516# return s

517

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

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

520 '''

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

522 if setters:

523 d = self.__dict__

524 # double-check that setters are Property_RO's

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

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

527 d[n] = v

528 else:

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

530 u += len(setters)

531 return u

532

533

534 class _NamedDict(ADict, _Named):

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

536 to the items.

537 '''

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

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

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

541 kwds = _name1__(kwds)

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

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

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

545 n, kwds = _name2__(**kwds)

546 if n:

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

548 ADict.__init__(self, kwds)

549

550 def __delattr__(self, name):

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

552 '''

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

554 ADict.pop(self, name)

555 elif name in (_name_, _name):

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

557 _Named.rename(self, NN)

558 else:

559 ADict.__delattr__(self, name)

560

561 def __getattr__(self, name):

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

563 '''

564 try:

565 return self[name]

566 except KeyError:

567 if name == _name_:

568 return _Named.name.fget(self)

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

570

571 def __getitem__(self, key):

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

573 '''

574 if key == _name_:

575 raise self._KeyError(key)

576 return ADict.__getitem__(self, key)

577

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

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

580 '''

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

582 t = Fmt.SQUARE(n, key)

583 if value:

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

585 return _KeyError(t)

586

587 def __setattr__(self, name, value):

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

589 '''

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

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

592 else:

593 ADict.__setattr__(self, name, value)

594

595 def __setitem__(self, key, value):

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

597 '''

598 if key == _name_:

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

600 ADict.__setitem__(self, key, value)

601

602

603 class _NamedEnum(_NamedDict):

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

605 restricted to valid keys.

606 '''

607 _item_Classes = ()

608

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

610 '''New C{_NamedEnum}.

611

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

613 values (C{type}).

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

615 '''

616 self._item_Classes = (Class,) + Classes

617 n = _name__(**name) or NN(Class.__name__, _s_) # _dunder_nameof

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

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

620

621 def __getattr__(self, name):

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

623 '''

624 return _NamedDict.__getattr__(self, name)

625

626 def __repr__(self):

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

628 '''

629 return self.toRepr()

630

631 def __str__(self):

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

633 '''

634 return self.toStr()

635

636 def _assert(self, **kwds):

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

638 '''

639 pypy = _isPyPy()

640 _isa = isinstance

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

642 if _isa(v, _LazyNamedEnumItem): # property

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

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

645 setattr(self.__class__, n, v)

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

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

648 and self.find(v) == n

649 else:

650 raise _TypeError(v, name=n)

651

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

653 '''Find a registered item.

654

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

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

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

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

659

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

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

662 '''

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

664 if v is item:

665 return k

666 return dflt

667

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

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

670

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

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

673

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

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

676 '''

677 # getattr needed to instantiate L{_LazyNamedEnumItem}

678 return getattr(self, name, dflt)

679

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

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

682

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

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

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

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

687 '''

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

689 _isa = isinstance

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

691 if _isa(p, _LazyNamedEnumItem):

692 _ = getattr(self, n)

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

694

695 def keys(self, **all_asorted):

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

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

698

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

700 '''

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

702 yield k

703

704 def popitem(self):

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

706

707 @return: The removed item.

708 '''

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

710

711 def register(self, item):

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

713

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

715

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

717

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

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

720 invalid name.

721

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

723 '''

724 if item is all or item is any:

725 _ = self.items(all=True)

726 n = item.__name__

727 else:

728 try:

729 n = item.name

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

731 raise ValueError()

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

733 n = _DOT_(_item_, _name_)

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

735 if n in self:

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

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

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

739 n = self._DOT_(n)

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

741 self[n] = item

742 return n

743

744 def unregister(self, name_or_item):

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

746

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

748

749 @return: The unregistered item.

750

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

752

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

754 '''

755 if isstr(name_or_item):

756 name = name_or_item

757 else:

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

759 if name is MISSING:

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

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

762 try:

763 item = ADict.pop(self, name)

764 except KeyError:

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

766 return self._zapitem(name, item)

767

768 pop = unregister

769

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

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

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

773 '''

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

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

776

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

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

779 '''

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

781

782 def values(self, **all_asorted):

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

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

785

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

787 '''

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

789 yield v

790

791 def _zapitem(self, name, item):

792 # remove _LazyNamedEnumItem property value if still present

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

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

795 item._enum = None

796 return item

797

798

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

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

801 '''

802 pass

803

804

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

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

807

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

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

810 '''

811 def _fget(inst):

812 # assert isinstance(inst, _NamedEnum)

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

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

815 item = inst[name]

816 except KeyError:

817 # instantiate an _NamedEnumItem, it self-registers

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

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

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

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

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

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

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

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

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

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

828 if isinstance(p, _LazyNamedEnumItem):

829 delattr(inst.__class__, name)

830 # assert isinstance(item, _NamedEnumItem)

831 return item

832

833 p = _LazyNamedEnumItem(_fget)

834 p.name = name

835 return p

836

837

838 class _NamedEnumItem(_NamedBase):

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

840 '''

841 _enum = None

842

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

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

845#

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

847# '''

848# return not self.__eq__(other)

849

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

851 def name(self):

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

853 '''

854 return self._name

855

856 @name.setter # PYCHOK setter!

857 def name(self, name):

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

859 '''

860 name = _name__(name) or _NN_

861 if self._enum:

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

863 if name:

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

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

874 self.name = name

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

876 enum.register(self)

877 self._enum = enum

878

879 def unregister(self):

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

881

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

883

884 @raise NameError: This item is unregistered.

885 '''

886 enum = self._enum

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

888 item = enum.unregister(self.name)

889 if item is not self: # PYCHOK no cover

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

891 raise _AssertionError(t)

892

893

894 class _NamedTuple(tuple, _Named):

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

896 attribute name access to the items.

897

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

899 but statically defined, lighter and limited.

900 '''

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

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

903

904 @note: Specify at least 2 item names.

905 '''

906 _Units_ = () # .units classes

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

908

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

910 '''

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

912

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

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

915

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

917 item of several more in other positional arguments.

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

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

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

921 I{silently} ignored.

922

923 @raise LenError: Unequal number of positional arguments and

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

925

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

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

928

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

930 or starts with C{underscore}.

931 '''

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

933 self = tuple.__new__(cls, args)

934 if not self._validated:

935 self._validate()

936

937 N = len(self._Names_)

938 if n != N:

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

940

941 if iteration_name:

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

943 if i is not None:

944 self._iteration = i

945 if name:

946 self.name = name

947 return self

948

949 def __delattr__(self, name):

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

951

952 @note: Items can not be deleted.

953 '''

954 if name in self._Names_:

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

956 raise _TypeError(t, txt=_immutable_)

957 elif name in (_name_, _name):

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

959 else:

960 tuple.__delattr__(self, name)

961

962 def __getattr__(self, name):

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

964 '''

965 try:

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

967 except IndexError as x:

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

969 except ValueError: # e.g. _iteration

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

971

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

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

974# '''

975# return tuple.__getitem__(self, index)

976

977 def __hash__(self):

978 return tuple.__hash__(self)

979

980 def __repr__(self):

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

982 '''

983 return self.toRepr()

984

985 def __setattr__(self, name, value):

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

987 '''

988 if name in self._Names_:

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

990 raise _TypeError(t, txt=_immutable_)

991 elif name in (_name_, _name):

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

993 else: # e.g. _iteration

994 tuple.__setattr__(self, name, value)

995

996 def __str__(self):

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

998 '''

999 return self.toStr()

1000

1001 def _DOT_(self, *names):

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

1003 '''

1004 return _DOT_(self.classname, *names)

1005

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

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

1008

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

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

1011

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

1013

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

1015 '''

1016 t = list(self)

1017 U = self._Units_

1018 if items:

1019 _ix = self._Names_.index

1020 _2U = _MODS.units._toUnit

1021 try:

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

1023 i = _ix(n)

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

1025 except ValueError: # bad item name

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

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

1028

1029 def items(self):

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

1031

1032 @see: Method C{.units}.

1033 '''

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

1035 yield n, v

1036

1037 iteritems = items

1038

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

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

1041

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

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

1044

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

1046

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

1048 '''

1049 U = self._Units_

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

1051 if n:

1052 R = Units + U[n:]

1053 if R != U:

1054 self._Units_ = R

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

1056

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

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

1059

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

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

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

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

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

1065

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

1067 '''

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

1069# if self.name:

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

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

1072

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

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

1075

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

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

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

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

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

1081

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

1083 '''

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

1085

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

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

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

1089

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

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

1092

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

1094

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

1096 '''

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

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

1099

1100 def units(self, **Error):

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

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

1103

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

1105

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

1107

1108 @see: Method C{.items}.

1109 '''

1110 _2U = _MODS.units._toUnit

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

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

1113

1114 iterunits = units

1115

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

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

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

1119 '''

1120 ns = self._Names_

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

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

1123 for i, n in enumerate(ns):

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

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

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

1127

1128 us = self._Units_

1129 if not isinstance(us, tuple):

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

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

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

1133 for i, u in enumerate(us):

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

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

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

1137

1138 self.__class__._validated = True

1139

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

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

1142 '''

1143 _xsubclassof(_NamedTuple, xTuple=xTuple)

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

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

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

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

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

1149 t = self + items

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

1151

1152

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

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

1155

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

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

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

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

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

1161

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

1163 '''

1164 try: # see .lazily._caller3

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

1166 n, f, s = _caller3(u)

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

1168 not n.startswith(_UNDER_)):

1169 if source:

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

1171 return n

1172 except (AttributeError, ValueError):

1173 pass

1174 return dflt

1175

1176

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

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

1179 '''

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

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

1182 return n, kwds

1183

1184

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

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

1187 '''

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

1189 if c:

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

1191 if self_name:

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

1193 return n

1194

1195

1196 def classname(inst, prefixed=None):

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

1198 module name.

1199

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

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

1202 function C{classnaming}.

1203

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

1205 '''

1206 if prefixed is None:

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

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

1209

1210

1211 def classnaming(prefixed=None):

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

1213

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

1215

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

1217 '''

1218 t = _Named._classnaming

1219 if prefixed in (True, False):

1220 _Named._classnaming = prefixed

1221 return t

1222

1223

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

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

1226 module name.

1227

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

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

1230 function C{classnaming}.

1231

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

1233 '''

1234 try:

1235 n = clas.__name__

1236 except AttributeError:

1237 n = clas if isstr(clas) else _dunder_name_

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

1239 try:

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

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

1242 except AttributeError:

1243 pass

1244 return n

1245

1246

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

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

1249# '''

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

1251# m = _MODS.errors

1252# raise m._UnexpectedError(**kwds)

1253# if name: # is given

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

1255# elif name__ is not None:

1256# n = getattr(name__, _dunder_name_, NN) # _xattr(name__, __name__=NN)

1257# else:

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

1259# if _or_nameof is not None and not n:

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

1261# return n # str or None or {}

1262

1263

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

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

1266 '''

1267 if name or kwds:

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

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

1270 raise _UnexpectedError(**kwds)

1271 return name if name or name is None else NN

1272

1273

1274 def _name1__(kwds_name, **name__or_nameof):

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

1276 '''

1277 if kwds_name or name__or_nameof:

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

1279 kwds_name.update(name=n)

1280 return kwds_name

1281

1282

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

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

1285 '''

1286 if name: # is given

1287 if isinstance(name, dict):

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

1289 n, kwds = _name2__(**kwds)

1290 else:

1291 n = str(name)

1292 elif name__ is not None:

1293 n = _dunder_nameof(name__, NN)

1294 else:

1295 n = name if name is None else NN

1296 if _or_nameof is not None and not n:

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

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

1299

1300

1301 def nameof(inst):

1302 '''Get the name of an instance.

1303

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

1305

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

1307 '''

1308 n = _xattr(inst, name=NN)

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

1310 try:

1311 n = inst.fget.__name__

1312 except AttributeError:

1313 n = NN

1314 return n

1315

1316

1317 def _notDecap(where):

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

1319 '''

1320 n = where.__name__

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

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

1323

1324

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

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

1327 '''

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

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

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

1331

1332

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

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

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

1336 '''

1337 if _std_NotImplemented:

1338 return NotImplemented

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

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

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

1342

1343

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

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

1346 property or for a missing caller feature.

1347

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

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

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

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

1352 C{B{up}=2}.

1353 '''

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

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

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

1357

1358

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

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

1361

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

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

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

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

1366 C{B{up}=2}.

1367 '''

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

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

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

1371

1372

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

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

1375 '''

1376 return arg

1377

1378

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

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

1381 '''

1382 if name__or_nameof:

1383 name = _name__(name, **name__or_nameof)

1384 if name and prefix:

1385 if enquote:

1386 name = repr(name)

1387 t = _SPACE_(prefix, name)

1388 else:

1389 t = prefix or name

1390 return t

1391

1392

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

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

1395

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

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

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

1399

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

1401 or if not named before.

1402 '''

1403 if name__or_nameof:

1404 name = _name__(name, **name__or_nameof)

1405 if name and isinstance(inst, _Named):

1406 if not inst.name:

1407 inst.name = name

1408 elif force:

1409 inst.rename(name)

1410 return inst

1411

1412

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

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

1415 '''

1416 if name_other: # and other is None

1417 name, other = _xkwds_item2(name_other)

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

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

1420 else:

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

1422 return other, name, up

1423

1424

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

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

1427 '''

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

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

1430

1431

1432 def _xvalid(name, underOK=False):

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

1434 '''

1435 return bool(name and isstr(name)

1436 and name != _name_

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

1438 and (not iskeyword(name))

1439 and isidentifier(name))

1440

1441

1442__all__ += _ALL_DOCS(_Named,

1443 _NamedBase, # _NamedDict,

1444 _NamedEnum, _NamedEnumItem,

1445 _NamedTuple)

1446

1447# **) MIT License

1448#

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

1450#

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

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

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

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

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

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

1457#

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

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

1460#

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

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

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

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

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

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

1467# OTHER DEALINGS IN THE SOFTWARE.