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 isclass, isidentifier, iskeyword, isstr, \

17 issubclassof, len2, _sizeof, _xcopy, _xdup, _zip

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

19 _IndexError, _IsnotError, itemsorted, LenError, \

20 _NameError, _NotImplementedError, _TypeError, \

21 _TypesError, _ValueError, UnitError, _xattr, \

22 _xkwds, _xkwds_get, _xkwds_pop, _xkwds_popitem

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

24 _COMMASPACE_, _doesn_t_exist_, _DOT_, _DUNDER_, \

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

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

27 _UNDER_, _valid_, _vs_, _dunder_nameof, _UNDER

28 from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _caller3, _getenv

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

30 _hasProperty, property_doc_, property_RO, \

31 _update_all, _update_attrs

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

33

34__all__ = _ALL_LAZY.named

35__version__ = '23.05.26'

36

37_COMMANL_ = _COMMA_ + _NL_

38_COMMASPACEDOT_ = _COMMASPACE_ + _DOT_

39_del_ = 'del'

40_item_ = 'item'

41_MRO_ = 'MRO'

42# __DUNDER gets mangled in class

43_name = _UNDER(_name_)

44_Names_ = '_Names_'

45_registered_ = 'registered' # PYCHOK used!

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

47_Units_ = '_Units_'

48

49

50 def _xjoined_(prefix, name):

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

52 '''

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

54

55

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

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

58

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

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

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

62

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

64 not named before.

65 '''

66 if name and isinstance(inst, _Named):

67 if not inst.name:

68 inst.name = name

69 elif force:

70 inst.rename(name)

71 return inst

72

73

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

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

76 '''

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

78 name, other = _xkwds_popitem(name_other)

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

80 other = other[0]

81 else:

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

83 return other, name, up

84

85

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

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

88 '''

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

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

91

92

93 def _xvalid(name, _OK=False):

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

95 '''

96 return True if (name and isstr(name)

97 and name != _name_

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

99 and (not iskeyword(name))

100 and isidentifier(name)) else False

101

102

103 class _Dict(dict):

104 '''(INTERNAL) An C{dict} with both key I{and}

105 attribute access to the C{dict} items.

106 '''

107 def __getattr__(self, name):

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

109 '''

110 try:

111 return self[name]

112 except KeyError:

113 pass

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

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

116

117 def __repr__(self):

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

119 '''

120 return self.toRepr()

121

122 def __str__(self):

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

124 '''

125 return self.toStr()

126

127 def set_(self, **items): # PYCHOK signature

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

129

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

131 '''

132 dict.update(self, items)

133

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

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

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

137 '''

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

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

140

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

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

143 function L{pygeodesy.fstr}.

144 '''

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

146

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

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

149 in C{_NamedDict} below.

150 '''

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

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

153

154

155 class _Named(object):

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

157 '''

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

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

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

161# _updates = 0 # OBSOLETE Property/property updates

162

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

164 '''Not implemented.'''

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

166

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

168 '''Not implemented.'''

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

170

171 def __repr__(self):

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

173 '''

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

175

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

177 '''Not implemented.'''

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

179

180 def __sizeof__(self): # PYCHOK not special in Python 2-

181 '''Return the current size of this instance C{bytes}.

182 '''

183 return _sizeof(self)

184

185 def __str__(self):

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

187 '''

188 return self.named2

189

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

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

192 function L{pygeodesy.fstr}.

193

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

195 @kwarg sep_COMMASPACE__Nones_True__pairs_kwds: Keyword argument for function

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

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

198

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

200

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

202 '''

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

204 return sep, kwds

205

206 sep, kwds = _sep_kwds(**sep_COMMASPACE__Nones_True__pairs_kwds)

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

208

209 @Property_RO

210 def classname(self):

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

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

213 '''

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

215

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

217 def classnaming(self):

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

219 '''

220 return self._classnaming

221

222 @classnaming.setter # PYCHOK setter!

223 def classnaming(self, prefixed):

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

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

226 '''

227 b = bool(prefixed)

228 if self._classnaming != b:

229 self._classnaming = b

230 _update_attrs(self, *_Named_Property_ROs)

231

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

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

234

235 @arg args: Optional, positional arguments.

236 @kwarg kwds: Optional, keyword arguments.

237

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

239 '''

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

241

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

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

244

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

246 a shallow copy (C{bool}).

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

248

249 @return: The copy (C{This class} or sub-class thereof).

250 '''

251 c = _xcopy(self, deep=deep)

252 if name:

253 c.rename(name)

254 return c

255

256 def _DOT_(self, *names):

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

258 '''

259 return _DOT_(self.name, *names)

260

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

262 '''Duplicate this instance, replacing some items.

263

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

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

266

267 @return: The duplicate (C{This class} or sub-class thereof).

268

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

270 '''

271 d = _xdup(self, **items)

272 if name:

273 d.rename(name=name)

274 return d

275

276 def _instr(self, name, prec, *attrs, **props_kwds):

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

278 '''

279 def _props_kwds(props=(), **kwds):

280 return props, kwds

281

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

283 if attrs:

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

285 prec=prec, ints=True)

286 props, kwds =_props_kwds(**props_kwds)

287 if props:

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

289 prec=prec, ints=True)

290 if kwds:

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

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

293

294 @property_RO

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

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

297 if not available or not applicable.

298

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

300 several, nested functions.

301 '''

302 return self._iteration

303

304 def methodname(self, which):

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

306

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

308 '''

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

310

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

312 def name(self):

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

314 '''

315 return self._name

316

317 @name.setter # PYCHOK setter!

318 def name(self, name):

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

320

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

322 '''

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

324 if not m:

325 self._name = n

326 elif n != m:

327 n = repr(n)

328 c = self.classname

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

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

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

332 n = _SPACE_(n, m)

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

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

335 # self.name = name or

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

337 # _Named(self).name = name

338

339 @Property_RO

340 def named(self):

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

342 '''

343 return self.name or self.classname

344

345 @Property_RO

346 def named2(self):

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

348 '''

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

350

351 @Property_RO

352 def named3(self):

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

354 '''

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

356

357 @Property_RO

358 def named4(self):

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

360 '''

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

362

363 def rename(self, name):

364 '''Change the name.

365

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

367

368 @return: The old name (C{str}).

369 '''

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

371 if n != m:

372 self._name = n

373 _update_attrs(self, *_Named_Property_ROs)

374 return m

375

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

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

378 '''

379 return repr(self)

380

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

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

383 '''

384 return str(self)

385

386 @deprecated_method

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

388 '''DEPRECATED, use method C{toRepr}.'''

389 return self.toRepr(**kwds)

390

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

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

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

394

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

396 '''

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

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

399

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

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

402

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

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

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

406

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

408 '''

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

410

411 def _xrenamed(self, inst):

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

413

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

415

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

417

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

419 '''

420 if not isinstance(inst, _Named):

421 raise _IsnotError(_valid_, inst=inst)

422

423 inst.rename(self.name)

424 return inst

425

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

427

428

429 class _NamedBase(_Named):

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

431 '''

432 def __repr__(self):

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

434 '''

435 return self.toRepr()

436

437 def __str__(self):

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

439 '''

440 return self.toStr()

441

442# def notImplemented(self, attr):

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

444#

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

446#

447# @raise NotImplementedError: No such attribute.

448# '''

449# c = self.__class__.__name__

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

451

452 def others(self, *other, **name_other_up): # see .points.LatLon_.others

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

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

455

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

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

458 keyword arguments.

459

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

461 C{class} or C{type}.

462

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

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

465 '''

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

467 other0 = other[0]

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

469 isinstance(self, other0.__class__):

470 return other0

471

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

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

474 isinstance(other, self.__class__):

475 return _xnamed(other, name)

476

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

478

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

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

481

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

483

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

485 '''

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

487# if self.name:

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

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

490

491# def toRepr(self, **kwds)

492# if kwds:

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

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

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

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

497

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

499 '''(INTERNAL) I{Must be overloaded}, see function C{notOverloaded}.

500 '''

501 notOverloaded(self, **kwds)

502

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

504# if kwds:

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

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

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

508# return s

509

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

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

512 '''

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

514 if setters:

515 d = self.__dict__

516 # double-check that setters are Property_RO's

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

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

519 d[n] = v

520 else:

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

522 u += len(setters)

523 return u

524

525

526 class _NamedDict(_Dict, _Named):

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

528 access to the items.

529 '''

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

531 if args: # args override kwds

532 if len(args) != 1:

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

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

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

536 if _name_ in kwds:

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

538 _Dict.__init__(self, kwds)

539

540 def __delattr__(self, name):

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

542 '''

543 if name in _Dict.keys(self):

544 _Dict.pop(name)

545 elif name in (_name_, _name):

546 # _Dict.__setattr__(self, name, NN)

547 _Named.rename(self, NN)

548 else:

549 _Dict.__delattr__(self, name)

550

551 def __getattr__(self, name):

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

553 '''

554 try:

555 return self[name]

556 except KeyError:

557 if name == _name_:

558 return _Named.name.fget(self)

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

560

561 def __getitem__(self, key):

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

563 '''

564 if key == _name_:

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

566 return _Dict.__getitem__(self, key)

567

568 def __setattr__(self, name, value):

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

570 '''

571 if name in _Dict.keys(self):

572 _Dict.__setitem__(self, name, value) # self[name] = value

573 else:

574 _Dict.__setattr__(self, name, value)

575

576 def __setitem__(self, key, value):

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

578 '''

579 if key == _name_:

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

581 _Dict.__setitem__(self, key, value)

582

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

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

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

586 '''

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

588

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

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

591 function L{pygeodesy.fstr}.

592 '''

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

594

595

596 class _NamedEnum(_NamedDict):

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

598 restricted to valid keys.

599 '''

600 _item_Classes = ()

601

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

603 '''New C{_NamedEnum}.

604

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

606 values (C{type}).

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

608 '''

609 self._item_Classes = (Class,) + Classes

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

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

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

613

614 def __getattr__(self, name):

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

616 '''

617 try:

618 return self[name]

619 except KeyError:

620 if name == _name_:

621 return _NamedDict.name.fget(self)

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

623

624 def __repr__(self):

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

626 '''

627 return self.toRepr()

628

629 def __str__(self):

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

631 '''

632 return self.toStr()

633

634 def _assert(self, **kwds):

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

636 '''

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

638 if isinstance(v, _LazyNamedEnumItem): # property

639 assert n is v.name

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

641 setattr(self.__class__, n, v)

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

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

644 and self.find(v) == n

645 else:

646 raise _TypeError(v, name=n)

647

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

649 '''Find a registered item.

650

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

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

653

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

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

656 '''

657 for k, v in self.items(): # or _Dict.items(self)

658 if v is item:

659 return k

660 return dflt

661

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

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

664

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

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

667

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

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

670 '''

671 # getattr needed to instantiate L{_LazyNamedEnumItem}

672 return getattr(self, name, dflt)

673

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

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

676

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

678 for only the currently I{registered} ones.

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

680 I{alphabetical, case-insensitive} order.

681 '''

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

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

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

685 if isinstance(p, _LazyNamedEnumItem)):

686 _ = getattr(self, n)

687 return itemsorted(self) if asorted else _Dict.items(self)

688

689 def keys(self, **all_asorted):

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

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

692

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

694 '''

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

696 yield k

697

698 def popitem(self):

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

700

701 @return: The removed item.

702 '''

703 return self._zapitem(*_Dict.pop(self))

704

705 def register(self, item):

706 '''Registed a new item.

707

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

709

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

711

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

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

714 empty or an invalid name.

715

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

717 '''

718 try:

719 n = item.name

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

721 raise ValueError

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

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

724 if n in self:

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

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

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

728 self[n] = item

729

730 def unregister(self, name_or_item):

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

732

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

734

735 @return: The unregistered item.

736

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

738

739 @raise ValueError: No such item.

740 '''

741 if isstr(name_or_item):

742 name = name_or_item

743 else:

744 name = self.find(name_or_item)

745 try:

746 item = _Dict.pop(self, name)

747 except KeyError:

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

749 return self._zapitem(name, item)

750

751 pop = unregister

752

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

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

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

756 '''

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

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

759

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

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

762 '''

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

764

765 def values(self, **all_asorted):

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

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

768

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

770 '''

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

772 yield v

773

774 def _zapitem(self, name, item):

775 # remove _LazyNamedEnumItem property value if still present

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

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

778 item._enum = None

779 return item

780

781

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

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

784 '''

785 pass

786

787

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

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

790

791 @see: Luciano Ramalho, "Fluent Python", page 636, O'Reilly, 2016,

792 "Coding a Property Factory", especially Example 19-24.

793 '''

794 def _fget(inst):

795 # assert isinstance(inst, _NamedEnum)

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

797 # item = inst.__dict__[name] # ... or _Dict

798 item = inst[name]

799 except KeyError:

800 # instantiate an _NamedEnumItem, it self-registers

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

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

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

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

805 inst.update({name: item}) # ... _Dict for Triaxials

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

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

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

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

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

811 if isinstance(p, _LazyNamedEnumItem):

812 delattr(inst.__class__, name)

813 # assert isinstance(item, _NamedEnumItem)

814 return item

815

816 p = _LazyNamedEnumItem(_fget)

817 p.name = name

818 return p

819

820

821 class _NamedEnumItem(_NamedBase):

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

823 '''

824 _enum = None

825

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

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

828#

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

830# '''

831# return not self.__eq__(other)

832

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

834 def name(self):

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

836 '''

837 return self._name

838

839 @name.setter # PYCHOK setter!

840 def name(self, name):

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

842 '''

843 if self._enum:

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

845 self._name = str(name)

846

847 def _register(self, enum, name):

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

849

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

851 start with a letter.

852 '''

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

854 self.name = name

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

856 enum.register(self)

857 self._enum = enum

858

859 def unregister(self):

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

861

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

863

864 @raise NameError: This item is unregistered.

865 '''

866 enum = self._enum

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

868 item = enum.unregister(self.name)

869 if item is not self:

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

871 raise _AssertionError(t)

872

873

874 class _NamedTuple(tuple, _Named):

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

876 attribute name access to the items.

877

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

879 but statically defined, lighter and limited.

880 '''

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

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

883

884 @note: Specify at least 2 item names.

885 '''

886 _Units_ = () # .units classes

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

888

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

890 '''

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

892

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

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

895

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

897 item of several more in other positional arguments.

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

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

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

901 I{silently} ignored.

902

903 @raise LenError: Unequal number of positional arguments and

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

905

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

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

908

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

910 or starts with C{underscore}.

911 '''

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

913 self = tuple.__new__(cls, args)

914 if not self._validated:

915 self._validate()

916

917 N = len(self._Names_)

918 if n != N:

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

920

921 if iteration_name:

922 self._kwdself(**iteration_name)

923 return self

924

925 def __delattr__(self, name):

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

927

928 @note: Items can not be deleted.

929 '''

930 if name in self._Names_:

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

932 elif name in (_name_, _name):

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

934 else:

935 tuple.__delattr__(self, name)

936

937 def __getattr__(self, name):

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

939 '''

940 try:

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

942 except IndexError:

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

944 except ValueError: # e.g. _iteration

945 return tuple.__getattribute__(self, name)

946

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

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

949# '''

950# return tuple.__getitem__(self, index)

951

952 def __repr__(self):

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

954 '''

955 return self.toRepr()

956

957 def __setattr__(self, name, value):

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

959 '''

960 if name in self._Names_:

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

962 elif name in (_name_, _name):

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

964 else: # e.g. _iteration

965 tuple.__setattr__(self, name, value)

966

967 def __str__(self):

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

969 '''

970 return self.toStr()

971

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

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

974

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

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

977

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

979

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

981 '''

982 tl = list(self)

983 if items:

984 _ix = self._Names_.index

985 try:

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

987 tl[_ix(n)] = v

988 except ValueError: # bad item name

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

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

991

992 def items(self):

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

994

995 @see: Method C{.units}.

996 '''

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

998 yield n, v

999

1000 iteritems = items

1001

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

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

1004 '''

1005 if iteration is not None:

1006 self._iteration = iteration

1007 if name:

1008 self.name = name

1009

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

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

1012

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

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

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

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

1017 @kwarg fmt: Optional, C{float} format (C{str}).

1018

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

1020 '''

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

1022# if self.name:

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

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

1025

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

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

1028

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

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

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

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

1033 @kwarg fmt: Optional C{float} format (C{str}).

1034

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

1036 '''

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

1038

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

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

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

1042

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

1044

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

1046

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

1048 '''

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

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

1051

1052 def units(self, Error=UnitError):

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

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

1055

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

1057

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

1059

1060 @see: Method C{.items}.

1061 '''

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

1063 if not (v is None or U is None

1064 or (isclass(U) and

1065 isinstance(v, U) and

1066 hasattr(v, _name_) and

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

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

1069 yield n, v

1070

1071 iterunits = units

1072

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

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

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

1076 '''

1077 ns = self._Names_

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

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

1080 for i, n in enumerate(ns):

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

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

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

1084

1085 us = self._Units_

1086 if not isinstance(us, tuple):

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

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

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

1090 for i, u in enumerate(us):

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

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

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

1094

1095 self.__class__._validated = True

1096

1097 def _xtend(self, xTuple, *items):

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

1099 '''

1100 if (issubclassof(xTuple, _NamedTuple) and

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

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

1103 return self._xnamed(xTuple(self + items)) # *(self + items)

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

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

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

1107

1108

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

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

1111

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

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

1114 @kwarg source: Include source file name and line

1115 number (C{bool}).

1116 @kwarg underOK: Private, internal callables are OK (C{bool}).

1117

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

1119 '''

1120 try: # see .lazily._caller3

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

1122 n, f, s = _caller3(u)

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

1124 not n.startswith(_UNDER_)):

1125 if source:

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

1127 return n

1128 except (AttributeError, ValueError):

1129 pass

1130 return dflt

1131

1132

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

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

1135 '''

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

1137 if c:

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

1139 if self_name:

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

1141 return n

1142

1143

1144 def classname(inst, prefixed=None):

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

1146 module name.

1147

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

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

1150 function C{classnaming}.

1151

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

1153 '''

1154 if prefixed is None:

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

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

1157

1158

1159 def classnaming(prefixed=None):

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

1161

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

1163

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

1165 '''

1166 t = _Named._classnaming

1167 if prefixed in (True, False):

1168 _Named._classnaming = prefixed

1169 return t

1170

1171

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

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

1174 module name.

1175

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

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

1178 function C{classnaming}.

1179

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

1181 '''

1182 try:

1183 n = clas.__name__

1184 except AttributeError:

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

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

1187 try:

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

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

1190 except AttributeError:

1191 pass

1192 return n

1193

1194

1195 def nameof(inst):

1196 '''Get the name of an instance.

1197

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

1199

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

1201 '''

1202 n = _xattr(inst, name=NN)

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

1204 try:

1205 n = inst.fget.__name__

1206 except AttributeError:

1207 n = NN

1208 return n

1209

1210

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

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

1213 '''

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

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

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

1217

1218

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

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

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

1222 '''

1223 if _std_NotImplemented:

1224 return NotImplemented

1225 u = _xkwds_pop(kwds, up=2)

1226 n = _DOT_(classname(inst), callername(up=u, underOK=True)) # source=True

1227 raise _NotImplementedError(unstr(n, *other, **kwds), txt=repr(inst))

1228

1229

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

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

1232 property or for a missing caller feature.

1233

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

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

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

1237 '''

1238 u = _xkwds_pop(kwds, up=2)

1239 n = _xkwds_pop(kwds, callername=NN) or callername(up=u)

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

1241 raise _NotImplementedError(t, txt=notImplemented.__name__.replace('I', ' i'))

1242

1243

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

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

1246

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

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

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

1250 '''

1251 u = _xkwds_pop(kwds, up=2)

1252 n = _xkwds_pop(kwds, callername=NN) or callername(up=u)

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

1254 raise _AssertionError(t, txt=notOverloaded.__name__.replace('O', ' o'))

1255

1256

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

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

1259 '''

1260 return arg

1261

1262

1263__all__ += _ALL_DOCS(_Named,

1264 _NamedBase, # _NamedDict,

1265 _NamedEnum, _NamedEnumItem,

1266 _NamedTuple)

1267

1268# **) MIT License

1269#

1270# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.

1271#

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

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

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

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

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

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

1278#

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

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

1281#

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

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

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

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

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

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

1288# OTHER DEALINGS IN THE SOFTWARE.

1289

1290# % env PYGEODESY_FOR_DOCS=1 python -m pygeodesy.named

1291# all 71 locals OK