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, _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.04'

36

37_COMMANL_ = _COMMA_ + _NL_

38_COMMASPACEDOT_ = _COMMASPACE_ + _DOT_

39_del_ = 'del'

40_item_ = 'item'

41_MRO_ = 'MRO'

42# __DUNDER gets mangled in class

43_name = _UNDER(_name_)

44_Names_ = '_Names_'

45_registered_ = 'registered' # PYCHOK used!

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

47_Units_ = '_Units_'

48

49

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 __str__(self):

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

182 '''

183 return self.named2

184

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

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

187 function L{pygeodesy.fstr}.

188

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

190 @kwarg sep_COMMASPACE__Nones_True__pairs_kwds: Keyword argument for function

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

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

193

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

195

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

197 '''

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

199 return sep, kwds

200

201 sep, kwds = _sep_kwds(**sep_COMMASPACE__Nones_True__pairs_kwds)

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

203

204 @Property_RO

205 def classname(self):

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

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

208 '''

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

210

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

212 def classnaming(self):

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

214 '''

215 return self._classnaming

216

217 @classnaming.setter # PYCHOK setter!

218 def classnaming(self, prefixed):

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

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

221 '''

222 b = bool(prefixed)

223 if self._classnaming != b:

224 self._classnaming = b

225 _update_attrs(self, *_Named_Property_ROs)

226

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

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

229

230 @arg args: Optional, positional arguments.

231 @kwarg kwds: Optional, keyword arguments.

232

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

234 '''

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

236

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

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

239

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

241 a shallow copy (C{bool}).

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

243

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

245 '''

246 c = _xcopy(self, deep=deep)

247 if name:

248 c.rename(name)

249 return c

250

251 def _DOT_(self, *names):

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

253 '''

254 return _DOT_(self.name, *names)

255

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

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

258

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

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

261

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

263

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

265 '''

266 d = _xdup(self, **items)

267 if name:

268 d.rename(name=name)

269 return d

270

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

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

273 '''

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

275 return props, kwds

276

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

278 if attrs:

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

280 prec=prec, ints=True)

281 props, kwds =_props_kwds(**props_kwds)

282 if props:

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

284 prec=prec, ints=True)

285 if kwds:

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

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

288

289 @property_RO

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

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

292 if not available or not applicable.

293

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

295 several, nested functions.

296 '''

297 return self._iteration

298

299 def methodname(self, which):

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

301

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

303 '''

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

305

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

307 def name(self):

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

309 '''

310 return self._name

311

312 @name.setter # PYCHOK setter!

313 def name(self, name):

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

315

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

317 '''

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

319 if not m:

320 self._name = n

321 elif n != m:

322 n = repr(n)

323 c = self.classname

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

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

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

327 n = _SPACE_(n, m)

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

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

330 # self.name = name or

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

332 # _Named(self).name = name

333

334 @Property_RO

335 def named(self):

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

337 '''

338 return self.name or self.classname

339

340 @Property_RO

341 def named2(self):

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

343 '''

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

345

346 @Property_RO

347 def named3(self):

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

349 '''

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

351

352 @Property_RO

353 def named4(self):

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

355 '''

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

357

358 def rename(self, name):

359 '''Change the name.

360

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

362

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

364 '''

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

366 if n != m:

367 self._name = n

368 _update_attrs(self, *_Named_Property_ROs)

369 return m

370

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

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

373 '''

374 return repr(self)

375

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

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

378 '''

379 return str(self)

380

381 @deprecated_method

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

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

384 return self.toRepr(**kwds)

385

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

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

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

389

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

391 '''

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

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

394

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

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

397

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

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

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

401

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

403 '''

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

405

406 def _xrenamed(self, inst):

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

408

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

410

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

412

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

414 '''

415 if not isinstance(inst, _Named):

416 raise _IsnotError(_valid_, inst=inst)

417

418 inst.rename(self.name)

419 return inst

420

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

422

423

424 class _NamedBase(_Named):

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

426 '''

427 def __repr__(self):

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

429 '''

430 return self.toRepr()

431

432 def __str__(self):

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

434 '''

435 return self.toStr()

436

437# def notImplemented(self, attr):

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

439#

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

441#

442# @raise NotImplementedError: No such attribute.

443# '''

444# c = self.__class__.__name__

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

446

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

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

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

450

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

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

453 keyword arguments.

454

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

456 C{class} or C{type}.

457

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

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

460 '''

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

462 other0 = other[0]

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

464 isinstance(self, other0.__class__):

465 return other0

466

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

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

469 isinstance(other, self.__class__):

470 return _xnamed(other, name)

471

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

473

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

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

476

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

478

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

480 '''

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

482# if self.name:

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

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

485

486# def toRepr(self, **kwds)

487# if kwds:

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

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

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

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

492

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

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

495 '''

496 notOverloaded(self, **kwds)

497

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

499# if kwds:

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

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

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

503# return s

504

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

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

507 '''

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

509 if setters:

510 d = self.__dict__

511 # double-check that setters are Property_RO's

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

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

514 d[n] = v

515 else:

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

517 u += len(setters)

518 return u

519

520

521 class _NamedDict(_Dict, _Named):

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

523 access to the items.

524 '''

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

526 if args: # args override kwds

527 if len(args) != 1:

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

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

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

531 if _name_ in kwds:

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

533 _Dict.__init__(self, kwds)

534

535 def __delattr__(self, name):

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

537 '''

538 if name in _Dict.keys(self):

539 _Dict.pop(name)

540 elif name in (_name_, _name):

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

542 _Named.rename(self, NN)

543 else:

544 _Dict.__delattr__(self, name)

545

546 def __getattr__(self, name):

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

548 '''

549 try:

550 return self[name]

551 except KeyError:

552 if name == _name_:

553 return _Named.name.fget(self)

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

555

556 def __getitem__(self, key):

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

558 '''

559 if key == _name_:

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

561 return _Dict.__getitem__(self, key)

562

563 def __setattr__(self, name, value):

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

565 '''

566 if name in _Dict.keys(self):

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

568 else:

569 _Dict.__setattr__(self, name, value)

570

571 def __setitem__(self, key, value):

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

573 '''

574 if key == _name_:

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

576 _Dict.__setitem__(self, key, value)

577

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

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

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

581 '''

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

583

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

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

586 function L{pygeodesy.fstr}.

587 '''

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

589

590

591 class _NamedEnum(_NamedDict):

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

593 restricted to valid keys.

594 '''

595 _item_Classes = ()

596

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

598 '''New C{_NamedEnum}.

599

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

601 values (C{type}).

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

603 '''

604 self._item_Classes = (Class,) + Classes

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

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

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

608

609 def __getattr__(self, name):

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

611 '''

612 try:

613 return self[name]

614 except KeyError:

615 if name == _name_:

616 return _NamedDict.name.fget(self)

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

618

619 def __repr__(self):

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

621 '''

622 return self.toRepr()

623

624 def __str__(self):

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

626 '''

627 return self.toStr()

628

629 def _assert(self, **kwds):

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

631 '''

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

633 if isinstance(v, _LazyNamedEnumItem): # property

634 assert n is v.name

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

636 setattr(self.__class__, n, v)

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

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

639 and self.find(v) == n

640 else:

641 raise _TypeError(v, name=n)

642

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

644 '''Find a registered item.

645

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

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

648

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

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

651 '''

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

653 if v is item:

654 return k

655 return dflt

656

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

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

659

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

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

662

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

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

665 '''

666 # getattr needed to instantiate L{_LazyNamedEnumItem}

667 return getattr(self, name, dflt)

668

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

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

671

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

673 for only the currently I{registered} ones.

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

675 I{alphabetical, case-insensitive} order.

676 '''

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

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

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

680 if isinstance(p, _LazyNamedEnumItem)):

681 _ = getattr(self, n)

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

683

684 def keys(self, **all_asorted):

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

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

687

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

689 '''

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

691 yield k

692

693 def popitem(self):

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

695

696 @return: The removed item.

697 '''

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

699

700 def register(self, item):

701 '''Registed a new item.

702

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

704

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

706

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

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

709 empty or an invalid name.

710

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

712 '''

713 try:

714 n = item.name

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

716 raise ValueError

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

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

719 if n in self:

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

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

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

723 self[n] = item

724

725 def unregister(self, name_or_item):

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

727

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

729

730 @return: The unregistered item.

731

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

733

734 @raise ValueError: No such item.

735 '''

736 if isstr(name_or_item):

737 name = name_or_item

738 else:

739 name = self.find(name_or_item)

740 try:

741 item = _Dict.pop(self, name)

742 except KeyError:

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

744 return self._zapitem(name, item)

745

746 pop = unregister

747

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

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

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

751 '''

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

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

754

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

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

757 '''

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

759

760 def values(self, **all_asorted):

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

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

763

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

765 '''

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

767 yield v

768

769 def _zapitem(self, name, item):

770 # remove _LazyNamedEnumItem property value if still present

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

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

773 item._enum = None

774 return item

775

776

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

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

779 '''

780 pass

781

782

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

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

785

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

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

788 '''

789 def _fget(inst):

790 # assert isinstance(inst, _NamedEnum)

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

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

793 item = inst[name]

794 except KeyError:

795 # instantiate an _NamedEnumItem, it self-registers

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

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

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

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

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

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

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

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

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

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

806 if isinstance(p, _LazyNamedEnumItem):

807 delattr(inst.__class__, name)

808 # assert isinstance(item, _NamedEnumItem)

809 return item

810

811 p = _LazyNamedEnumItem(_fget)

812 p.name = name

813 return p

814

815

816 class _NamedEnumItem(_NamedBase):

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

818 '''

819 _enum = None

820

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

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

823#

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

825# '''

826# return not self.__eq__(other)

827

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

829 def name(self):

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

831 '''

832 return self._name

833

834 @name.setter # PYCHOK setter!

835 def name(self, name):

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

837 '''

838 if self._enum:

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

840 self._name = str(name)

841

842 def _register(self, enum, name):

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

844

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

846 start with a letter.

847 '''

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

849 self.name = name

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

851 enum.register(self)

852 self._enum = enum

853

854 def unregister(self):

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

856

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

858

859 @raise NameError: This item is unregistered.

860 '''

861 enum = self._enum

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

863 item = enum.unregister(self.name)

864 if item is not self:

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

866 raise _AssertionError(t)

867

868

869 class _NamedTuple(tuple, _Named):

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

871 attribute name access to the items.

872

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

874 but statically defined, lighter and limited.

875 '''

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

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

878

879 @note: Specify at least 2 item names.

880 '''

881 _Units_ = () # .units classes

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

883

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

885 '''

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

887

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

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

890

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

892 item of several more in other positional arguments.

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

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

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

896 I{silently} ignored.

897

898 @raise LenError: Unequal number of positional arguments and

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

900

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

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

903

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

905 or starts with C{underscore}.

906 '''

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

908 self = tuple.__new__(cls, args)

909 if not self._validated:

910 self._validate()

911

912 N = len(self._Names_)

913 if n != N:

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

915

916 if iteration_name:

917 self._kwdself(**iteration_name)

918 return self

919

920 def __delattr__(self, name):

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

922

923 @note: Items can not be deleted.

924 '''

925 if name in self._Names_:

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

927 elif name in (_name_, _name):

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

929 else:

930 tuple.__delattr__(self, name)

931

932 def __getattr__(self, name):

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

934 '''

935 try:

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

937 except IndexError:

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

939 except ValueError: # e.g. _iteration

940 return tuple.__getattribute__(self, name)

941

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

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

944# '''

945# return tuple.__getitem__(self, index)

946

947 def __repr__(self):

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

949 '''

950 return self.toRepr()

951

952 def __setattr__(self, name, value):

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

954 '''

955 if name in self._Names_:

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

957 elif name in (_name_, _name):

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

959 else: # e.g. _iteration

960 tuple.__setattr__(self, name, value)

961

962 def __str__(self):

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

964 '''

965 return self.toStr()

966

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

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

969

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

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

972

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

974

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

976 '''

977 tl = list(self)

978 if items:

979 _ix = self._Names_.index

980 try:

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

982 tl[_ix(n)] = v

983 except ValueError: # bad item name

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

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

986

987 def items(self):

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

989

990 @see: Method C{.units}.

991 '''

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

993 yield n, v

994

995 iteritems = items

996

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

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

999 '''

1000 if iteration is not None:

1001 self._iteration = iteration

1002 if name:

1003 self.name = name

1004

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

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

1007

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

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

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

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

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

1013

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

1015 '''

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

1017# if self.name:

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

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

1020

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

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

1023

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

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

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

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

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

1029

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

1031 '''

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

1033

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

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

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

1037

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

1039

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

1041

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

1043 '''

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

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

1046

1047 def units(self, Error=UnitError):

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

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

1050

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

1052

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

1054

1055 @see: Method C{.items}.

1056 '''

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

1058 if not (v is None or U is None

1059 or (isclass(U) and

1060 isinstance(v, U) and

1061 hasattr(v, _name_) and

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

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

1064 yield n, v

1065

1066 iterunits = units

1067

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

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

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

1071 '''

1072 ns = self._Names_

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

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

1075 for i, n in enumerate(ns):

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

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

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

1079

1080 us = self._Units_

1081 if not isinstance(us, tuple):

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

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

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

1085 for i, u in enumerate(us):

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

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

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

1089

1090 self.__class__._validated = True

1091

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

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

1094 '''

1095 if (issubclassof(xTuple, _NamedTuple) and

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

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

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

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

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

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

1102

1103

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

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

1106

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

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

1109 @kwarg source: Include source file name and line

1110 number (C{bool}).

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

1112

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

1114 '''

1115 try: # see .lazily._caller3

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

1117 n, f, s = _caller3(u)

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

1119 not n.startswith(_UNDER_)):

1120 if source:

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

1122 return n

1123 except (AttributeError, ValueError):

1124 pass

1125 return dflt

1126

1127

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

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

1130 '''

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

1132 if c:

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

1134 if self_name:

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

1136 return n

1137

1138

1139 def classname(inst, prefixed=None):

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

1141 module name.

1142

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

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

1145 function C{classnaming}.

1146

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

1148 '''

1149 if prefixed is None:

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

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

1152

1153

1154 def classnaming(prefixed=None):

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

1156

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

1158

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

1160 '''

1161 t = _Named._classnaming

1162 if prefixed in (True, False):

1163 _Named._classnaming = prefixed

1164 return t

1165

1166

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

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

1169 module name.

1170

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

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

1173 function C{classnaming}.

1174

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

1176 '''

1177 try:

1178 n = clas.__name__

1179 except AttributeError:

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

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

1182 try:

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

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

1185 except AttributeError:

1186 pass

1187 return n

1188

1189

1190 def nameof(inst):

1191 '''Get the name of an instance.

1192

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

1194

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

1196 '''

1197 n = _xattr(inst, name=NN)

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

1199 try:

1200 n = inst.fget.__name__

1201 except AttributeError:

1202 n = NN

1203 return n

1204

1205

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

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

1208 '''

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

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

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

1212

1213

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

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

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

1217 '''

1218 if _std_NotImplemented:

1219 return NotImplemented

1220 u = _xkwds_pop(kwds, up=2)

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

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

1223

1224

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

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

1227 property or for a missing caller feature.

1228

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

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

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

1232 '''

1233 u = _xkwds_pop(kwds, up=2)

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

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

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

1237

1238

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

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

1241

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

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

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

1245 '''

1246 u = _xkwds_pop(kwds, up=2)

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

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

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

1250

1251

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

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

1254 '''

1255 return arg

1256

1257

1258__all__ += _ALL_DOCS(_Named,

1259 _NamedBase, # _NamedDict,

1260 _NamedEnum, _NamedEnumItem,

1261 _NamedTuple)

1262

1263# **) MIT License

1264#

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

1266#

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

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

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

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

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

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

1273#

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

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

1276#

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

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

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

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

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

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

1283# OTHER DEALINGS IN THE SOFTWARE.

1284

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

1286# all 71 locals OK