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.ecef import EcefKarney # _MODS

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

20 _IndexError, _KeyError, LenError, _NameError, \

21 _NotImplementedError, _TypeError, _TypesError, \

22 _UnexpectedError, UnitError, _ValueError, \

23 _xattr, _xkwds, _xkwds_item2, _xkwds_pop2

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

25 _sizeof, _under

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

27 _COMMASPACE_, _doesn_t_exist_, _DOT_, _DUNDER_, \

28 _DUNDER_name_, _EQUAL_, _exists_, _immutable_, _name_, \

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

30 _UNDER_, _vs_

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

32# from pygeodesy.ltp import Ltp, _toLocal, _toLtp # _MODS

33# from pygeodesy.ltpTuples import Aer, Enu, Ned # _MODS

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

35 _update_all, property_doc_, Property_RO, property_RO, \

36 _update_attrs, property_ROver

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

38# from pygeodesy.units import _toUnit # _MODS

39

40__all__ = _ALL_LAZY.named

41__version__ = '24.12.05'

42

43_COMMANL_ = _COMMA_ + _NL_

44_COMMASPACEDOT_ = _COMMASPACE_ + _DOT_

45_del_ = 'del'

46_item_ = 'item'

47_MRO_ = 'MRO'

48# __DUNDER gets mangled in class

49_name = _under(_name_)

50_Names_ = '_Names_'

51_registered_ = 'registered' # PYCHOK used!

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

53_such_ = 'such'

54_Units_ = '_Units_'

55_UP = 2

56

57

58 class ADict(dict):

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

60 the C{dict} items.

61 '''

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

63

64 def __getattr__(self, name):

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

66 '''

67 try:

68 return self[name]

69 except KeyError:

70 if name == _name_:

71 return NN

72 raise self._AttributeError(name)

73

74 def __repr__(self):

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

76 '''

77 return self.toRepr()

78

79 def __setattr__(self, name, value):

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

81 '''

82 try:

83 if self[name] != value:

84 self[name] = value

85 except KeyError:

86 dict.__setattr__(self, name, value)

87

88 def __str__(self):

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

90 '''

91 return self.toStr()

92

93 def _AttributeError(self, name):

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

95 '''

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

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

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

99

100 @property_RO

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

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

103 C{None} if not available/applicable.

104 '''

105 return self._iteration

106

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

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

109

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

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

112 '''

113 if iteration is not None:

114 self._iteration = iteration

115 if items:

116 dict.update(self, items)

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

118

119 def toRepr(self, **prec_fmt):

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

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

122 '''

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

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

125

126 def toStr(self, **prec_fmt):

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

128 function L{pygeodesy.fstr}.

129 '''

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

131

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

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

134 '''

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

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

137

138

139 class _Named(object):

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

141 '''

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

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

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

145# _updates = 0 # OBSOLETE Property/property updates

146

147 def __format__(self, fmt): # PYCHOK no cover

148 '''Not implemented.'''

149 return _NotImplemented(self, fmt)

150

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

152 '''Not implemented.'''

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

154

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

156 '''Not implemented.'''

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

158

159 def __repr__(self):

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

161 '''

162 return Fmt.repr_at(self)

163

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

165 '''Not implemented.'''

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

167

168 def __str__(self):

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

170 '''

171 return self.named2

172

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

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

175 function L{pygeodesy.fstr}.

176

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

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

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

180 or C{None}-valued attributes.

181

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

183

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

185 '''

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

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

188

189 @Property_RO

190 def classname(self):

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

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

193 '''

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

195

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

197 def classnaming(self):

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

199 '''

200 return self._classnaming

201

202 @classnaming.setter # PYCHOK setter!

203 def classnaming(self, prefixed):

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

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

206 '''

207 b = bool(prefixed)

208 if self._classnaming != b:

209 self._classnaming = b

210 _update_attrs(self, *_Named_Property_ROs)

211

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

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

214

215 @arg args: Optional, positional arguments.

216 @kwarg kwds: Optional, keyword arguments.

217

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

219 '''

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

221

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

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

224

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

226 copy (C{bool}).

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

228

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

230 '''

231 c = _xcopy(self, deep=deep)

232 if name:

233 _ = c.rename(name)

234 return c

235

236 def _DOT_(self, *names):

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

238 '''

239 return _DOT_(self.name, *names)

240

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

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

243

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

245 (C{bool}).

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

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

248

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

250

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

252 '''

253 n = self.name

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

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

256 if m != n:

257 d.rename(m) # zap _Named_Property_ROs

258# if items:

259# _update_all(d)

260 return d

261

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

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

264 '''

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

266 return fmt, prec, props, sep, kwds

267

268 name, kwds = _name2__(**fmt_prec_props_sep_name__kwds)

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

270

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

272 if attrs:

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

274 prec=prec, ints=True, fmt=fmt)

275 if props:

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

277 prec=prec, ints=True)

278 if kwds:

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

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

281

282 @property_RO

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

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

285 if not available or not applicable.

286

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

288 several, nested functions.

289 '''

290 return self._iteration

291

292 def methodname(self, which):

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

294

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

296 '''

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

298

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

300 def name(self):

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

302 '''

303 return self._name

304

305 @name.setter # PYCHOK setter!

306 def name(self, name):

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

308

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

310 '''

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

312 if not m:

313 self._name = n

314 elif n != m:

315 n = repr(n)

316 c = self.classname

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

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

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

320 n = _SPACE_(n, m)

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

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

323 # self.name = name or

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

325 # _Named(self).name = name

326

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

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

329 '''

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

331

332 def _name1__(self, kwds):

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

334 '''

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

336

337 @Property_RO

338 def named(self):

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

340 '''

341 return self.name or self.classname

342

343# @Property_RO

344# def named_(self):

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

346# '''

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

348

349 @Property_RO

350 def named2(self):

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

352 '''

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

354

355 @Property_RO

356 def named3(self):

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

358 '''

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

360

361 @Property_RO

362 def named4(self):

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

364 '''

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

366

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

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

369 '''

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

371

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

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

374 '''

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

376

377 def rename(self, name):

378 '''Change the name.

379

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

381

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

383 '''

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

385 if n != m:

386 self._name = n

387 _update_attrs(self, *_Named_Property_ROs)

388 return m

389

390 def renamed(self, name):

391 '''Change the name.

392

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

394

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

396 '''

397 _ = self.rename(name)

398 return self

399

400 @property_RO

401 def sizeof(self):

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

403 '''

404 return _sizeof(self)

405

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

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

408 '''

409 return repr(self)

410

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

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

413 '''

414 return str(self)

415

416 @deprecated_method

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

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

419 return self.toRepr(**kwds)

420

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

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

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

424#

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

426# '''

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

428

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

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

431

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

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

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

435

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

437 or if not named before.

438 '''

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

440

441 def _xrenamed(self, inst):

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

443

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

445

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

447

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

449 '''

450 _xinstanceof(_Named, inst=inst) # assert

451 return inst.renamed(self.name)

452

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

454

455

456 class _NamedBase(_Named):

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

458 '''

459 def __repr__(self):

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

461 '''

462 return self.toRepr()

463

464 def __str__(self):

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

466 '''

467 return self.toStr()

468

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

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

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

472

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

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

475 keyword arguments.

476

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

478 C{class} or C{type}.

479

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

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

482 '''

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

484 other0 = other[0]

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

486 isinstance(self, other0.__class__):

487 return other0

488

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

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

491 isinstance(other, self.__class__):

492 return _xnamed(other, name)

493

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

495

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

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

498

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

500

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

502 '''

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

504# if self.name:

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

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

507

508# def toRepr(self, **kwds)

509# if kwds:

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

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

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

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

514

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

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

517 notOverloaded(self, **kwds)

518

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

520# if kwds:

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

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

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

524# return s

525

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

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

528 '''

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

530 if setters:

531 d = self.__dict__

532 # double-check that setters are Property_RO's

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

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

535 d[n] = v

536 else:

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

538 u += len(setters)

539 return u

540

541

542 class _NamedDict(ADict, _Named):

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

544 to the items.

545 '''

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

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

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

549 kwds = _name1__(kwds)

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

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

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

553 n, kwds = _name2__(**kwds)

554 if n:

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

556 ADict.__init__(self, kwds)

557

558 def __delattr__(self, name):

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

560 '''

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

562 ADict.pop(self, name)

563 elif name in (_name_, _name):

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

565 _Named.rename(self, NN)

566 else:

567 ADict.__delattr__(self, name)

568

569 def __getattr__(self, name):

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

571 '''

572 try:

573 return self[name]

574 except KeyError:

575 if name == _name_:

576 return _Named.name.fget(self)

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

578

579 def __getitem__(self, key):

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

581 '''

582 if key == _name_:

583 raise self._KeyError(key)

584 return ADict.__getitem__(self, key)

585

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

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

588 '''

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

590 t = Fmt.SQUARE(n, key)

591 if value:

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

593 return _KeyError(t)

594

595 def __setattr__(self, name, value):

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

597 '''

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

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

600 else:

601 ADict.__setattr__(self, name, value)

602

603 def __setitem__(self, key, value):

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

605 '''

606 if key == _name_:

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

608 ADict.__setitem__(self, key, value)

609

610

611 class _NamedEnum(_NamedDict):

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

613 restricted to valid keys.

614 '''

615 _item_Classes = ()

616

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

618 '''New C{_NamedEnum}.

619

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

621 values (C{type}).

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

623 '''

624 self._item_Classes = (Class,) + Classes

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

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

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

628

629 def __getattr__(self, name):

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

631 '''

632 return _NamedDict.__getattr__(self, name)

633

634 def __repr__(self):

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

636 '''

637 return self.toRepr()

638

639 def __str__(self):

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

641 '''

642 return self.toStr()

643

644 def _assert(self, **kwds):

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

646 '''

647 pypy = _isPyPy()

648 _isa = isinstance

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

650 if _isa(v, _LazyNamedEnumItem): # property

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

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

653 setattr(self.__class__, n, v)

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

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

656 and self.find(v) == n

657 else:

658 raise _TypeError(v, name=n)

659

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

661 '''Find a registered item.

662

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

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

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

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

667

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

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

670 '''

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

672 if v is item:

673 return k

674 return dflt

675

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

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

678

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

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

681

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

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

684 '''

685 # getattr needed to instantiate L{_LazyNamedEnumItem}

686 return getattr(self, name, dflt)

687

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

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

690

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

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

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

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

695 '''

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

697 _isa = isinstance

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

699 if _isa(p, _LazyNamedEnumItem):

700 _ = getattr(self, n)

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

702

703 def keys(self, **all_asorted):

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

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

706

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

708 '''

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

710 yield k

711

712 def popitem(self):

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

714

715 @return: The removed item.

716 '''

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

718

719 def register(self, item):

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

721

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

723

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

725

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

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

728 invalid name.

729

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

731 '''

732 if item is all or item is any:

733 _ = self.items(all=True)

734 n = item.__name__

735 else:

736 try:

737 n = item.name

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

739 raise ValueError()

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

741 n = _DOT_(_item_, _name_)

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

743 if n in self:

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

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

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

747 n = self._DOT_(n)

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

749 self[n] = item

750 return n

751

752 def unregister(self, name_or_item):

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

754

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

756

757 @return: The unregistered item.

758

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

760

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

762 '''

763 if isstr(name_or_item):

764 name = name_or_item

765 else:

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

767 if name is MISSING:

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

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

770 try:

771 item = ADict.pop(self, name)

772 except KeyError:

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

774 return self._zapitem(name, item)

775

776 pop = unregister

777

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

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

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

781 '''

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

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

784

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

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

787 '''

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

789

790 def values(self, **all_asorted):

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

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

793

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

795 '''

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

797 yield v

798

799 def _zapitem(self, name, item):

800 # remove _LazyNamedEnumItem property value if still present

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

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

803 item._enum = None

804 return item

805

806

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

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

809 '''

810 pass

811

812

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

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

815

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

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

818 '''

819 def _fget(inst):

820 # assert isinstance(inst, _NamedEnum)

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

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

823 item = inst[name]

824 except KeyError:

825 # instantiate an _NamedEnumItem, it self-registers

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

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

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

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

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

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

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

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

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

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

836 if isinstance(p, _LazyNamedEnumItem):

837 delattr(inst.__class__, name)

838 # assert isinstance(item, _NamedEnumItem)

839 return item

840

841 p = _LazyNamedEnumItem(_fget)

842 p.name = name

843 return p

844

845

846 class _NamedEnumItem(_NamedBase):

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

848 '''

849 _enum = None

850

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

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

853#

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

855# '''

856# return not self.__eq__(other)

857

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

859 def name(self):

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

861 '''

862 return self._name

863

864 @name.setter # PYCHOK setter!

865 def name(self, name):

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

867 '''

868 name = _name__(name) or _NN_

869 if self._enum:

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

871 if name:

872 self._name = name

873

874 def _register(self, enum, name):

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

876

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

878 start with a letter.

879 '''

880 name = _name__(name)

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

882 self.name = name

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

884 enum.register(self)

885 self._enum = enum

886

887 def unregister(self):

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

889

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

891

892 @raise NameError: This item is unregistered.

893 '''

894 enum = self._enum

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

896 item = enum.unregister(self.name)

897 if item is not self: # PYCHOK no cover

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

899 raise _AssertionError(t)

900

901

902 class _NamedLocal(object):

903 '''(INTERNAL) Base class for C{CartesianBase}, C{Ecef9Tuple} and C{LatLonBase}.

904 '''

905

906 @property_ROver

907 def Ecef(self):

908 '''Get the ECEF I{class} (L{EcefKarney}), I{once}.

909 '''

910 return _MODS.ecef.EcefKarney

911

912 @property_RO

913 def _ecef9(self):

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

915 notOverloaded(self)

916

917 @Property_RO

918 def _Ltp(self):

919 '''(INTERNAL) Cache this instance' LTP (L{Ltp}).

920 '''

921 return self._ltp.Ltp(self._ecef9, ecef=self.Ecef(self.datum), name=self.name)

922

923 @property_ROver

924 def _ltp(self):

925 '''(INTERNAL) Get module L{pygeodesy.ltp}, I{once}.

926 '''

927 return _MODS.ltp

928

929 def _ltp_toLocal(self, ltp, Cls_and_kwds, **nam_Cls): # overloaded in C{Ecef9Tuple}

930 '''(INTERNAL) Invoke C{ltp._toLocal}.

931 '''

932 Cls, kwds = self._ltp_toLocal2(Cls_and_kwds, **nam_Cls)

933 return self._ltp._toLocal(self, ltp, Cls, kwds) # self._ecef9

934

935 def _ltp_toLocal2(self, Cls_and_kwds, _None=None, **nam_Cls):

936 '''(INTERNAL) Return 2-tuple C{(Cls, kwds)}.

937 '''

938 Cls, kwds = _xkwds_pop2(Cls_and_kwds, **nam_Cls)

939 if Cls is not _None: # validate Cls

940 n, LoC = _xkwds_item2(nam_Cls)

941 if LoC is not Cls:

942 _xsubclassof(LoC, **{n: Cls})

943 return Cls, kwds

944

945 @property_ROver

946 def _ltpTuples(self):

947 '''(INTERNAL) Get module L{pygeodesy.ltpTuples}, I{once}.

948 '''

949 return _MODS.ltpTuples

950

951 def toAer(self, ltp=None, **Aer_and_kwds):

952 '''Convert this instance to I{local} I{Azimuth, Elevation, slant Range} (AER) components.

953

954 @kwarg ltp: The I{local tangent plane} (LTP) to use (L{Ltp}), overriding this

955 instance' L{LTP<pygeodesy.named._NamedLocal.toLtp>}.

956 @kwarg Aer_and_kwds: Optional AER class C{B{Aer}=}L{Aer<pygeodesy.ltpTuples.Aer>}

957 to use and optionally, additional B{C{Aer}} keyword arguments.

958

959 @return: An B{C{Aer}} instance.

960

961 @raise TypeError: Invalid B{C{ltp}}.

962

963 @see: Method L{toLocal<pygeodesy.named._NamedLocal.toLocal>}.

964 '''

965 return self._ltp_toLocal(ltp, Aer_and_kwds, Aer=self._ltpTuples.Aer)

966

967 def toEnu(self, ltp=None, **Enu_and_kwds):

968 '''Convert this instance to I{local} I{East, North, Up} (ENU) components.

969

970 @kwarg ltp: The I{local tangent plane} (LTP) to use (L{Ltp}), overriding this

971 instance' L{LTP<pygeodesy.named._NamedLocal.toLtp>}.

972 @kwarg Enu_and_kwds: Optional ENU class C{B{Enu}=}L{Enu<pygeodesy.ltpTuples.Enu>}

973 to use and optionally, additional B{C{Enu}} keyword arguments.

974

975 @return: An B{C{Enu}} instance.

976

977 @raise TypeError: Invalid B{C{ltp}}.

978

979 @see: Method L{toLocal<pygeodesy.named._NamedLocal.toLocal>}.

980 '''

981 return self._ltp_toLocal(ltp, Enu_and_kwds, Enu=self._ltpTuples.Enu)

982

983 def toLocal(self, Xyz=None, ltp=None, **Xyz_kwds):

984 '''Convert this instance to I{local} components in a I{local tangent plane} (LTP)

985

986 @kwarg Xyz: Optional I{local} components class (L{XyzLocal}, L{Aer},

987 L{Enu}, L{Ned}) or C{None}.

988 @kwarg ltp: The I{local tangent plane} (LTP) to use (L{Ltp}), overriding this

989 cartesian's L{LTP<pygeodesy.named._NamedLocal.toLtp>}.

990 @kwarg Xyz_kwds: Optionally, additional B{C{Xyz}} keyword arguments, ignored

991 if C{B{Xyz} is None}.

992

993 @return: An B{C{Xyz}} instance or a L{Local9Tuple}C{(x, y, z, lat, lon,

994 height, ltp, ecef, M)} if C{B{Xyz} is None} (with C{M=None}).

995

996 @raise TypeError: Invalid B{C{ltp}}.

997 '''

998 return self._ltp_toLocal(ltp, Xyz_kwds, Xyz=Xyz, _None=Xyz)

999

1000 def toLtp(self, Ecef=None, **name):

1001 '''Return the I{local tangent plane} (LTP) for this instance.

1002

1003 @kwarg Ecef: Optional ECEF I{class} (L{EcefKarney}, ... L{EcefYou}), overriding

1004 this instance' L{Ecef<pygeodesy.named._NamedLocal.Ecef>}.

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

1006

1007 @return: An B{C{Ltp}} instance.

1008 '''

1009 return self._ltp._toLtp(self, Ecef, self._ecef9, name) # needs self.Ecef and self._Ltp

1010

1011 def toNed(self, ltp=None, **Ned_and_kwds):

1012 '''Convert this instance to I{local} I{North, East, Down} (NED) components.

1013

1014 @kwarg ltp: The I{local tangent plane} (LTP) to use (L{Ltp}), overriding this

1015 instance' L{LTP<pygeodesy.named._NamedLocal.toLtp>}.

1016 @kwarg Ned_and_kwds: Optional NED class C{B{Ned}=}L{Ned<pygeodesy.ltpTuples.Ned>}

1017 to use and optionally, additional B{C{Ned}} keyword arguments.

1018

1019 @return: An B{C{Ned}} instance.

1020

1021 @raise TypeError: Invalid B{C{ltp}}.

1022

1023 @see: Method L{toLocal<pygeodesy.named._NamedLocal.toLocal>}.

1024 '''

1025 return self._ltp_toLocal(ltp, Ned_and_kwds, Ned=self._ltpTuples.Ned)

1026

1027 def toXyz(self, ltp=None, **Xyz_and_kwds):

1028 '''Convert this instance to I{local} I{X, Y, Z} (XYZ) components.

1029

1030 @kwarg ltp: The I{local tangent plane} (LTP) to use (L{Ltp}), overriding this

1031 instance' L{LTP<pygeodesy.named._NamedLocal.toLtp>}.

1032 @kwarg Xyz_and_kwds: Optional XYZ class C{B{Xyz}=}L{Xyz<pygeodesy.ltpTuples.XyzLocal>}

1033 to use and optionally, additional B{C{Xyz}} keyword arguments.

1034

1035 @return: An B{C{Xyz}} instance.

1036

1037 @raise TypeError: Invalid B{C{ltp}}.

1038

1039 @see: Method L{toLocal<pygeodesy.named._NamedLocal.toLocal>}.

1040 '''

1041 return self._ltp_toLocal(ltp, Xyz_and_kwds, Xyz=self._ltpTuples.XyzLocal)

1042

1043

1044# from pygeodesy.props import _NamedProperty

1045

1046

1047 class _NamedTuple(tuple, _Named):

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

1049 attribute name access to the items.

1050

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

1052 but statically defined, lighter and limited.

1053 '''

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

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

1056

1057 @note: Specify at least 2 item names.

1058 '''

1059 _Units_ = () # .units classes

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

1061

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

1063 '''

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

1065

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

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

1068

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

1070 item of several more in other positional arguments.

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

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

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

1074 I{silently} ignored.

1075

1076 @raise LenError: Unequal number of positional arguments and

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

1078

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

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

1081

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

1083 or starts with C{underscore}.

1084 '''

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

1086 self = tuple.__new__(cls, args)

1087 if not self._validated:

1088 self._validate()

1089

1090 N = len(self._Names_)

1091 if n != N:

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

1093

1094 if iteration_name:

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

1096 if i is not None:

1097 self._iteration = i

1098 if name:

1099 self.name = name

1100 return self

1101

1102 def __delattr__(self, name):

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

1104

1105 @note: Items can not be deleted.

1106 '''

1107 if name in self._Names_:

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

1109 raise _TypeError(t, txt=_immutable_)

1110 elif name in (_name_, _name):

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

1112 else:

1113 tuple.__delattr__(self, name)

1114

1115 def __getattr__(self, name):

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

1117 '''

1118 try:

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

1120 except IndexError as x:

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

1122 except ValueError: # e.g. _iteration

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

1124

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

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

1127# '''

1128# return tuple.__getitem__(self, index)

1129

1130 def __hash__(self):

1131 return tuple.__hash__(self)

1132

1133 def __repr__(self):

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

1135 '''

1136 return self.toRepr()

1137

1138 def __setattr__(self, name, value):

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

1140 '''

1141 if name in self._Names_:

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

1143 raise _TypeError(t, txt=_immutable_)

1144 elif name in (_name_, _name):

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

1146 else: # e.g. _iteration

1147 tuple.__setattr__(self, name, value)

1148

1149 def __str__(self):

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

1151 '''

1152 return self.toStr()

1153

1154 def _DOT_(self, *names):

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

1156 '''

1157 return _DOT_(self.classname, *names)

1158

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

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

1161

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

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

1164

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

1166

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

1168 '''

1169 t = list(self)

1170 U = self._Units_

1171 if items:

1172 _ix = self._Names_.index

1173 _2U = _MODS.units._toUnit

1174 try:

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

1176 i = _ix(n)

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

1178 except ValueError: # bad item name

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

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

1181

1182 def items(self):

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

1184

1185 @see: Method C{.units}.

1186 '''

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

1188 yield n, v

1189

1190 iteritems = items

1191

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

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

1194

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

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

1197

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

1199

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

1201 '''

1202 U = self._Units_

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

1204 if n:

1205 R = Units + U[n:]

1206 if R != U:

1207 self._Units_ = R

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

1209

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

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

1212

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

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

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

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

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

1218

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

1220 '''

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

1222# if self.name:

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

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

1225

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

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

1228

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

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

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

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

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

1234

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

1236 '''

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

1238

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

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

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

1242

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

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

1245

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

1247

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

1249 '''

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

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

1252

1253 def units(self, **Error):

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

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

1256

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

1258

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

1260

1261 @see: Method C{.items}.

1262 '''

1263 _2U = _MODS.units._toUnit

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

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

1266

1267 iterunits = units

1268

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

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

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

1272 '''

1273 ns = self._Names_

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

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

1276 for i, n in enumerate(ns):

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

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

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

1280

1281 us = self._Units_

1282 if not isinstance(us, tuple):

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

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

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

1286 for i, u in enumerate(us):

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

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

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

1290

1291 self.__class__._validated = True

1292

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

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

1295 '''

1296 _xsubclassof(_NamedTuple, xTuple=xTuple)

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

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

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

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

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

1302 t = self + items

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

1304

1305

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

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

1308

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

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

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

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

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

1314

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

1316 '''

1317 try: # see .lazily._caller3

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

1319 n, f, s = _caller3(u)

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

1321 not n.startswith(_UNDER_)):

1322 if source:

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

1324 return n

1325 except (AttributeError, ValueError):

1326 pass

1327 return dflt

1328

1329

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

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

1332 '''

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

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

1335 return n, kwds

1336

1337

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

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

1340 '''

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

1342 if c:

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

1344 if self_name:

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

1346 return n

1347

1348

1349 def classname(inst, prefixed=None):

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

1351 module name.

1352

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

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

1355 function C{classnaming}.

1356

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

1358 '''

1359 if prefixed is None:

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

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

1362

1363

1364 def classnaming(prefixed=None):

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

1366

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

1368

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

1370 '''

1371 t = _Named._classnaming

1372 if prefixed in (True, False):

1373 _Named._classnaming = prefixed

1374 return t

1375

1376

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

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

1379 module name.

1380

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

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

1383 function C{classnaming}.

1384

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

1386 '''

1387 try:

1388 n = clas.__name__

1389 except AttributeError:

1390 n = clas if isstr(clas) else _DUNDER_name_

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

1392 try:

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

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

1395 except AttributeError:

1396 pass

1397 return n

1398

1399

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

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

1402# '''

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

1404# m = _MODS.errors

1405# raise m._UnexpectedError(**kwds)

1406# if name: # is given

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

1408# elif name__ is not None:

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

1410# else:

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

1412# if _or_nameof is not None and not n:

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

1414# return n # str or None or {}

1415

1416

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

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

1419 '''

1420 if name or kwds:

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

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

1423 raise _UnexpectedError(**kwds)

1424 return name if name or name is None else NN

1425

1426

1427 def _name1__(kwds_name, **name__or_nameof):

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

1429 '''

1430 if kwds_name or name__or_nameof:

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

1432 kwds_name.update(name=n)

1433 return kwds_name

1434

1435

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

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

1438 '''

1439 if name: # is given

1440 if isinstance(name, dict):

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

1442 n, kwds = _name2__(**kwds)

1443 else:

1444 n = str(name)

1445 elif name__ is not None:

1446 n = _DUNDER_nameof(name__, NN)

1447 else:

1448 n = name if name is None else NN

1449 if _or_nameof is not None and not n:

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

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

1452

1453

1454 def nameof(inst):

1455 '''Get the name of an instance.

1456

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

1458

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

1460 '''

1461 n = _xattr(inst, name=NN)

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

1463 try:

1464 n = inst.fget.__name__

1465 except AttributeError:

1466 n = NN

1467 return n

1468

1469

1470 def _notDecap(where):

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

1472 '''

1473 n = where.__name__

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

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

1476

1477

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

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

1480 '''

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

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

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

1484

1485

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

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

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

1489 '''

1490 if _std_NotImplemented:

1491 return NotImplemented

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

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

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

1495

1496

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

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

1499 property or for a missing caller feature.

1500

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

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

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

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

1505 C{B{up}=2}.

1506 '''

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

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

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

1510

1511

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

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

1514

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

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

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

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

1519 C{B{up}=2}.

1520 '''

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

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

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

1524

1525

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

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

1528 '''

1529 return arg

1530

1531

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

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

1534 '''

1535 if name__or_nameof:

1536 name = _name__(name, **name__or_nameof)

1537 if name and prefix:

1538 if enquote:

1539 name = repr(name)

1540 t = _SPACE_(prefix, name)

1541 else:

1542 t = prefix or name

1543 return t

1544

1545

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

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

1548

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

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

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

1552

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

1554 or if not named before.

1555 '''

1556 if name__or_nameof:

1557 name = _name__(name, **name__or_nameof)

1558 if name and isinstance(inst, _Named):

1559 if not inst.name:

1560 inst.name = name

1561 elif force:

1562 inst.rename(name)

1563 return inst

1564

1565

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

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

1568 '''

1569 if name_other: # and other is None

1570 name, other = _xkwds_item2(name_other)

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

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

1573 else:

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

1575 return other, name, up

1576

1577

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

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

1580 '''

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

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

1583

1584

1585 def _xvalid(name, underOK=False):

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

1587 '''

1588 return bool(name and isstr(name)

1589 and name != _name_

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

1591 and (not iskeyword(name))

1592 and isidentifier(name))

1593

1594

1595__all__ += _ALL_DOCS(_Named,

1596 _NamedBase, # _NamedDict,

1597 _NamedEnum, _NamedEnumItem,

1598 _NamedLocal,

1599 _NamedTuple)

1600

1601# **) MIT License

1602#

1603# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved.

1604#

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

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

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

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

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

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

1611#

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

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

1614#

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

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

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

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

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

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

1621# OTHER DEALINGS IN THE SOFTWARE.