1

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

3

4 u'''Some, basic definitions, functions and dependencies.

5

6 Use env variable C{PYGEODESY_XPACKAGES} to avoid import of dependencies

7 C{geographiclib}, C{numpy} and/or C{scipy}. Set C{PYGEODESY_XPACKAGES}

8 to a comma-separated list of package names to be excluded from import.

9'''

10# make sure int/int division yields float quotient

11 from __future__ import division

12 division = 1 / 2 # .albers, .azimuthal, .constants, etc., .utily

13 if not division:

14 raise ImportError('%s 1/2 == %s' % ('division', division))

15 del division

16

17 from pygeodesy.errors import _AttributeError, _ImportError, _NotImplementedError, \

18 _TypeError, _TypesError, _ValueError, _xAssertionError, \

19 _xkwds_get

20 from pygeodesy.interns import MISSING, NN, _1_, _by_, _COMMA_, _DOT_, _DEPRECATED_, \

21 _ELLIPSIS4_, _enquote, _EQUAL_, _in_, _invalid_, _N_A_, \

22 _not_scalar_, _SPACE_, _UNDER_, _version_, _version_info

23 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, _FOR_DOCS, \

24 _getenv, LazyImportError, _sys, _sys_version_info2

25

26 from copy import copy as _copy, deepcopy as _deepcopy

27 from math import copysign as _copysign

28 import inspect as _inspect

29

30__all__ = _ALL_LAZY.basics

31__version__ = '24.02.21'

32

33_0_0 = 0.0 # in .constants

34_below_ = 'below'

35_list_tuple_types = (list, tuple)

36_list_tuple_set_types = (list, tuple, set)

37_odd_ = 'odd'

38_PYGEODESY_XPACKAGES_ = 'PYGEODESY_XPACKAGES'

39_required_ = 'required'

40

41 try: # Luciano Ramalho, "Fluent Python", O'Reilly, 2016 p. 395, 2022 p. 577+

42 from numbers import Integral as _Ints, Real as _Scalars # .units

43 except ImportError:

44 try:

45 _Ints = int, long # int objects (C{tuple})

46 except NameError: # Python 3+

47 _Ints = int, # int objects (C{tuple})

48 _Scalars = _Ints + (float,)

49

50 try:

51 try: # use C{from collections.abc import ...} in Python 3.9+

52 from collections.abc import Sequence as _Sequence # in .points

53 except ImportError: # no .abc in Python 3.8- and 2.7-

54 from collections import Sequence as _Sequence # in .points

55 if isinstance([], _Sequence) and isinstance((), _Sequence):

56 # and isinstance(range(1), _Sequence):

57 _Seqs = _Sequence

58 else:

59 raise ImportError() # _AssertionError

60 except ImportError:

61 _Sequence = tuple # immutable for .points._Basequence

62 _Seqs = list, _Sequence # range for function len2 below

63

64

65 def _passarg(arg): # in .auxilats.auxLat

66 '''(INTERNAL) Helper, no-op.

67 '''

68 return arg

69

70

71 def _passargs(*args): # in .utily

72 '''(INTERNAL) Helper, no-op.

73 '''

74 return args

75

76

77 try:

78 _Bytes = unicode, bytearray # PYCHOK expected

79 _Strs = basestring, str # XXX , bytes

80 str2ub = ub2str = _passarg # avoids UnicodeDecodeError

81

82 def _Xstr(exc): # PYCHOK no cover

83 '''I{Invoke only with caught ImportError} B{C{exc}}.

84

85 C{... "can't import name _distributor_init" ...}

86

87 only for C{numpy}, C{scipy} import errors occurring

88 on arm64 Apple Silicon running macOS' Python 2.7.16?

89 '''

90 t = str(exc)

91 if '_distributor_init' in t:

92 from sys import exc_info

93 from traceback import extract_tb

94 tb = exc_info()[2] # 3-tuple (type, value, traceback)

95 t4 = extract_tb(tb, 1)[0] # 4-tuple (file, line, name, 'import ...')

96 t = _SPACE_("can't", t4[3] or _N_A_)

97 del tb, t4

98 return t

99

100 except NameError: # Python 3+

101 from pygeodesy.interns import _utf_8_

102

103 _Bytes = bytes, bytearray

104 _Strs = str, # tuple

105 _Xstr = str

106

107 def str2ub(sb):

108 '''Convert C{str} to C{unicode bytes}.

109 '''

110 if isinstance(sb, _Strs):

111 sb = sb.encode(_utf_8_)

112 return sb

113

114 def ub2str(ub):

115 '''Convert C{unicode bytes} to C{str}.

116 '''

117 if isinstance(ub, _Bytes):

118 ub = str(ub.decode(_utf_8_))

119 return ub

120

121

122 def _args_kwds_names(func):

123 '''(INTERNAL) Get a C{func}'s args and kwds names, including

124 C{self} for methods.

125

126 @note: Python 2 may I{not} include the C{*args} nor the

127 C{**kwds} names.

128 '''

129 try:

130 args_kwds = _inspect.signature(func).parameters.keys()

131 except AttributeError: # .signature new Python 3+

132 args_kwds = _inspect.getargspec(func).args

133 return tuple(args_kwds)

134

135

136 def clips(sb, limit=50, white=NN):

137 '''Clip a string to the given length limit.

138

139 @arg sb: String (C{str} or C{bytes}).

140 @kwarg limit: Length limit (C{int}).

141 @kwarg white: Optionally, replace all whitespace (C{str}).

142

143 @return: The clipped or unclipped B{C{sb}}.

144 '''

145 T = type(sb)

146 if len(sb) > limit > 8:

147 h = limit // 2

148 sb = T(_ELLIPSIS4_).join((sb[:h], sb[-h:]))

149 if white: # replace whitespace

150 sb = T(white).join(sb.split())

151 return sb

152

153

154 def copysign0(x, y):

155 '''Like C{math.copysign(x, y)} except C{zero}, I{unsigned}.

156

157 @return: C{math.copysign(B{x}, B{y})} if B{C{x}} else

158 C{type(B{x})(0)}.

159 '''

160 return _copysign(x, (y if y else 0)) if x else copytype(0, x)

161

162

163 def copytype(x, y):

164 '''Return the value of B{x} as C{type} of C{y}.

165

166 @return: C{type(B{y})(B{x})}.

167 '''

168 return type(y)(x if x else _0_0)

169

170

171 def halfs2(str2):

172 '''Split a string in 2 halfs.

173

174 @arg str2: String to split (C{str}).

175

176 @return: 2-Tuple C{(_1st, _2nd)} half (C{str}).

177

178 @raise ValueError: Zero or odd C{len(B{str2})}.

179 '''

180 h, r = divmod(len(str2), 2)

181 if r or not h:

182 raise _ValueError(str2=str2, txt=_odd_)

183 return str2[:h], str2[h:]

184

185

186 def int1s(x):

187 '''Count the number of 1-bits in an C{int}, I{unsigned}.

188

189 @note: C{int1s(-B{x}) == int1s(abs(B{x}))}.

190 '''

191 try:

192 return x.bit_count() # Python 3.10+

193 except AttributeError:

194 # bin(-x) = '-' + bin(abs(x))

195 return bin(x).count(_1_)

196

197

198 def isbool(obj):

199 '''Check whether an object is C{bool}ean.

200

201 @arg obj: The object (any C{type}).

202

203 @return: C{True} if B{C{obj}} is C{bool}ean,

204 C{False} otherwise.

205 '''

206 return isinstance(obj, bool) # and (obj is False

207# or obj is True)

208

209 assert not (isbool(1) or isbool(0) or isbool(None)) # PYCHOK 2

210

211 if _FOR_DOCS: # XXX avoid epydoc Python 2.7 error

212

213 def isclass(obj):

214 '''Return C{True} if B{C{obj}} is a C{class} or C{type}.

215

216 @see: Python's C{inspect.isclass}.

217 '''

218 return _inspect.isclass(obj)

219 else:

220 isclass = _inspect.isclass

221

222

223 def isCartesian(obj, ellipsoidal=None):

224 '''Is B{C{obj}} some C{Cartesian}?

225

226 @arg obj: The object (any C{type}).

227 @kwarg ellipsoidal: If C{None}, return the type of any C{Cartesian},

228 if C{True}, only an ellipsoidal C{Cartesian type}

229 or if C{False}, only a spherical C{Cartesian type}.

230

231 @return: C{type(B{obj}} if B{C{obj}} is a C{Cartesian} instance of

232 the required type, C{False} if a C{Cartesian} of an other

233 type or C{None} otherwise.

234 '''

235 if ellipsoidal is not None:

236 try:

237 return obj.ellipsoidalCartesian if ellipsoidal else obj.sphericalCartesian

238 except AttributeError:

239 return None

240 return isinstanceof(obj, _MODS.cartesianBase.CartesianBase)

241

242

243 def iscomplex(obj):

244 '''Check whether an object is a C{complex} or complex C{str}.

245

246 @arg obj: The object (any C{type}).

247

248 @return: C{True} if B{C{obj}} is C{complex}, otherwise

249 C{False}.

250 '''

251 try: # hasattr('conjugate'), hasattr('real') and hasattr('imag')

252 return isinstance(obj, complex) or (isstr(obj)

253 and isinstance(complex(obj), complex)) # numbers.Complex?

254 except (TypeError, ValueError):

255 return False

256

257

258 def isDEPRECATED(obj):

259 '''Return C{True} if C{B{obj}} is a C{DEPRECATED} class, method

260 or function, C{False} if not or C{None} if undetermined.

261 '''

262 try: # XXX inspect.getdoc(obj)

263 return bool(obj.__doc__.lstrip().startswith(_DEPRECATED_))

264 except AttributeError:

265 return None

266

267

268 def isfloat(obj):

269 '''Check whether an object is a C{float} or float C{str}.

270

271 @arg obj: The object (any C{type}).

272

273 @return: C{True} if B{C{obj}} is a C{float}, otherwise

274 C{False}.

275 '''

276 try:

277 return isinstance( obj, float) or (isstr(obj)

278 and isinstance(float(obj), float))

279 except (TypeError, ValueError):

280 return False

281

282

283 try:

284 isidentifier = str.isidentifier # Python 3, must be str

285 except AttributeError: # Python 2-

286

287 def isidentifier(obj):

288 '''Return C{True} if B{C{obj}} is a Python identifier.

289 '''

290 return bool(obj and isstr(obj)

291 and obj.replace(_UNDER_, NN).isalnum()

292 and not obj[:1].isdigit())

293

294

295 def isinstanceof(obj, *classes):

296 '''Is B{C{ob}} an instance of one of the C{classes}?

297

298 @arg obj: The instance (any C{type}).

299 @arg classes: One or more classes (C{class}).

300

301 @return: C{type(B{obj}} if B{C{obj}} is an instance

302 of the B{C{classes}}, C{None} otherwise.

303 '''

304 return type(obj) if isinstance(obj, classes) else None

305

306

307 def isint(obj, both=False):

308 '''Check for C{int} type or an integer C{float} value.

309

310 @arg obj: The object (any C{type}).

311 @kwarg both: If C{true}, check C{float} and L{Fsum}

312 type and value (C{bool}).

313

314 @return: C{True} if B{C{obj}} is C{int} or I{integer}

315 C{float} or L{Fsum}, C{False} otherwise.

316

317 @note: Both C{isint(True)} and C{isint(False)} return

318 C{False} (and no longer C{True}).

319 '''

320 if isinstance(obj, _Ints) and not isbool(obj):

321 return True

322 elif both: # and isinstance(obj, (float, Fsum))

323 try: # NOT , _Scalars) to include Fsum!

324 return obj.is_integer()

325 except AttributeError:

326 pass # XXX float(int(obj)) == obj?

327 return False

328

329

330 try:

331 from keyword import iskeyword # Python 2.7+

332 except ImportError:

333

334 def iskeyword(unused):

335 '''Not Implemented, C{False} always.

336 '''

337 return False

338

339

340 def isLatLon(obj, ellipsoidal=None):

341 '''Is B{C{obj}} some C{LatLon}?

342

343 @arg obj: The object (any C{type}).

344 @kwarg ellipsoidal: If C{None}, return the type of any C{LatLon},

345 if C{True}, only an ellipsoidal C{LatLon type}

346 or if C{False}, only a spherical C{LatLon type}.

347

348 @return: C{type(B{obj}} if B{C{obj}} is a C{LatLon} instance of

349 the required type, C{False} if a C{LatLon} of an other

350 type or {None} otherwise.

351 '''

352 if ellipsoidal is not None:

353 try:

354 return obj.ellipsoidalLatLon if ellipsoidal else obj.sphericalLatLon

355 except AttributeError:

356 return None

357 return isinstanceof(obj, _MODS.latlonBase.LatLonBase)

358

359

360 def islistuple(obj, minum=0):

361 '''Check for list or tuple C{type} with a minumal length.

362

363 @arg obj: The object (any C{type}).

364 @kwarg minum: Minimal C{len} required C({int}).

365

366 @return: C{True} if B{C{obj}} is C{list} or C{tuple} with

367 C{len} at least B{C{minum}}, C{False} otherwise.

368 '''

369 return isinstance(obj, _list_tuple_types) and len(obj) >= minum

370

371

372 def isNvector(obj, ellipsoidal=None):

373 '''Is B{C{obj}} some C{Nvector}?

374

375 @arg obj: The object (any C{type}).

376 @kwarg ellipsoidal: If C{None}, return the type of any C{Nvector},

377 if C{True}, only an ellipsoidal C{Nvector type}

378 or if C{False}, only a spherical C{Nvector type}.

379

380 @return: C{type(B{obj}} if B{C{obj}} is an C{Nvector} instance of

381 the required type, C{False} if an C{Nvector} of an other

382 type or {None} otherwise.

383 '''

384 if ellipsoidal is not None:

385 try:

386 return obj.ellipsoidalNvector if ellipsoidal else obj.sphericalNvector

387 except AttributeError:

388 return None

389 return isinstanceof(obj, _MODS.nvectorBase.NvectorBase)

390

391

392 def isodd(x):

393 '''Is B{C{x}} odd?

394

395 @arg x: Value (C{scalar}).

396

397 @return: C{True} if B{C{x}} is odd,

398 C{False} otherwise.

399 '''

400 return bool(int(x) & 1) # == bool(int(x) % 2)

401

402

403 def isscalar(obj):

404 '''Check for scalar types.

405

406 @arg obj: The object (any C{type}).

407

408 @return: C{True} if B{C{obj}} is C{scalar}, C{False} otherwise.

409 '''

410 return isinstance(obj, _Scalars) and not isbool(obj)

411

412

413 def issequence(obj, *excls):

414 '''Check for sequence types.

415

416 @arg obj: The object (any C{type}).

417 @arg excls: Classes to exclude (C{type}), all positional.

418

419 @note: Excluding C{tuple} implies excluding C{namedtuple}.

420

421 @return: C{True} if B{C{obj}} is a sequence, C{False} otherwise.

422 '''

423 return isinstance(obj, _Seqs) and not (excls and isinstance(obj, excls))

424

425

426 def isstr(obj):

427 '''Check for string types.

428

429 @arg obj: The object (any C{type}).

430

431 @return: C{True} if B{C{obj}} is C{str}, C{False} otherwise.

432 '''

433 return isinstance(obj, _Strs)

434

435

436 def issubclassof(Sub, *Supers):

437 '''Check whether a class is a sub-class of some other class(es).

438

439 @arg Sub: The sub-class (C{class}).

440 @arg Supers: One or more C(super) classes (C{class}).

441

442 @return: C{True} if B{C{Sub}} is a sub-class of any B{C{Supers}},

443 C{False} if not (C{bool}) or C{None} if B{C{Sub}} is not

444 a class or if no B{C{Supers}} are given or none of those

445 are a class.

446 '''

447 if isclass(Sub):

448 t = tuple(S for S in Supers if isclass(S))

449 if t:

450 return bool(issubclass(Sub, t))

451 return None

452

453

454 def itemsorted(adict, *items_args, **asorted_reverse):

455 '''Return the items of C{B{adict}} sorted I{alphabetically,

456 case-insensitively} and in I{ascending} order.

457

458 @arg items_args: Optional positional argument(s) for method

459 C{B{adict}.items(B*{items_args})}.

460 @kwarg asorted_reverse: Use keyword argument C{B{asorted}=False}

461 for I{case-sensitive} sorting and C{B{reverse}=True}

462 for results in C{descending} order.

463 '''

464 def _ins(item):

465 return item[0].lower()

466

467 def _key_rev(asorted=True, reverse=False):

468 return (_ins if asorted else None), reverse

469

470 key, rev = _key_rev(**asorted_reverse)

471 items = adict.items(*items_args) if items_args else adict.items()

472 return sorted(items, reverse=rev, key=key)

473

474

475 def len2(items):

476 '''Make built-in function L{len} work for generators, iterators,

477 etc. since those can only be started exactly once.

478

479 @arg items: Generator, iterator, list, range, tuple, etc.

480

481 @return: 2-Tuple C{(n, items)} of the number of items (C{int})

482 and the items (C{list} or C{tuple}).

483 '''

484 if not isinstance(items, _Seqs): # NOT hasattr(items, '__len__'):

485 items = list(items)

486 return len(items), items

487

488

489 def map1(fun1, *xs): # XXX map_

490 '''Apply a single-argument function to each B{C{xs}} and

491 return a C{tuple} of results.

492

493 @arg fun1: 1-Arg function (C{callable}).

494 @arg xs: Arguments (C{any positional}).

495

496 @return: Function results (C{tuple}).

497 '''

498 return tuple(map(fun1, xs))

499

500

501 def map2(fun, *xs):

502 '''Apply a function to arguments and return a C{tuple} of results.

503

504 Unlike Python 2's built-in L{map}, Python 3+ L{map} returns a

505 L{map} object, an iterator-like object which generates the

506 results only once. Converting the L{map} object to a tuple

507 maintains the Python 2 behavior.

508

509 @arg fun: Function (C{callable}).

510 @arg xs: Arguments (C{list, tuple, ...}).

511

512 @return: Function results (C{tuple}).

513 '''

514 return tuple(map(fun, *xs))

515

516

517 def neg(x, neg0=None):

518 '''Negate C{x} and optionally, negate C{0.0} and C{-0.0}.

519

520 @kwarg neg0: Defines the return value for zero C{B{x}}: if C{None}

521 return C{0.0}, if C{True} return C{NEG0 if B{x}=0.0}

522 and C{0.0 if B{x}=NEG0} or if C{False} return C{B{x}}

523 I{as-is} (C{bool} or C{None}).

524

525 @return: C{-B{x} if B{x} else 0.0, NEG0 or B{x}}.

526 '''

527 return (-x) if x else (_0_0 if neg0 is None else (x if not neg0 else

528 (_0_0 if signBit(x) else _MODS.constants.NEG0)))

529

530

531 def neg_(*xs):

532 '''Negate all C{xs} with L{neg}.

533

534 @return: A C{map(neg, B{xs})}.

535 '''

536 return map(neg, xs)

537

538

539 def _req_d_by(where, **name): # in .basics

540 '''(INTERNAL) Get the fully qualified name.

541 '''

542 m = _MODS.named.modulename(where, prefixed=True)

543 if name:

544 n = _xkwds_get(name, name=NN)

545 if n:

546 m = _DOT_(m, n)

547 return _SPACE_(_required_, _by_, m)

548

549

550 def _reverange(n, stop=-1, step=-1):

551 '''(INTERNAL) Reversed range yielding C{n-1, n-1-step, ..., stop+1}.

552 '''

553 return range(n - 1, stop, step)

554

555

556 def signBit(x):

557 '''Return C{signbit(B{x})}, like C++.

558

559 @return: C{True} if C{B{x} < 0} or C{NEG0} (C{bool}).

560 '''

561 return x < 0 or _MODS.constants.isneg0(x)

562

563

564 def _signOf(x, ref): # in .fsums

565 '''(INTERNAL) Return the sign of B{C{x}} versus B{C{ref}}.

566 '''

567 return +1 if x > ref else (-1 if x < ref else 0)

568

569

570 def signOf(x):

571 '''Return sign of C{x} as C{int}.

572

573 @return: -1, 0 or +1 (C{int}).

574 '''

575 try:

576 s = x.signOf() # Fsum instance?

577 except AttributeError:

578 s = _signOf(x, 0)

579 return s

580

581

582 def _sizeof(inst):

583 '''(INTERNAL) Recursively size an C{inst}ance.

584

585 @return: Instance' size in bytes (C{int}),

586 ignoring class attributes and

587 counting duplicates only once or

588 C{None}.

589

590 @note: With C{PyPy}, the size is always C{None}.

591 '''

592 try:

593 _zB = _sys.getsizeof

594 _zD = _zB(None) # get some default

595 except TypeError: # PyPy3.10

596 return None

597

598 def _zR(s, iterable):

599 z, _s = 0, s.add

600 for o in iterable:

601 i = id(o)

602 if i not in s:

603 _s(i)

604 z += _zB(o, _zD)

605 if isinstance(o, dict):

606 z += _zR(s, o.keys())

607 z += _zR(s, o.values())

608 elif isinstance(o, _list_tuple_set_types):

609 z += _zR(s, o)

610 else:

611 try: # size instance' attr values only

612 z += _zR(s, o.__dict__.values())

613 except AttributeError: # None, int, etc.

614 pass

615 return z

616

617 return _zR(set(), (inst,))

618

619

620 def splice(iterable, n=2, **fill):

621 '''Split an iterable into C{n} slices.

622

623 @arg iterable: Items to be spliced (C{list}, C{tuple}, ...).

624 @kwarg n: Number of slices to generate (C{int}).

625 @kwarg fill: Optional fill value for missing items.

626

627 @return: A generator for each of B{C{n}} slices,

628 M{iterable[i::n] for i=0..n}.

629

630 @raise TypeError: Invalid B{C{n}}.

631

632 @note: Each generated slice is a C{tuple} or a C{list},

633 the latter only if the B{C{iterable}} is a C{list}.

634

635 @example:

636

637 >>> from pygeodesy import splice

638

639 >>> a, b = splice(range(10))

640 >>> a, b

641 ((0, 2, 4, 6, 8), (1, 3, 5, 7, 9))

642

643 >>> a, b, c = splice(range(10), n=3)

644 >>> a, b, c

645 ((0, 3, 6, 9), (1, 4, 7), (2, 5, 8))

646

647 >>> a, b, c = splice(range(10), n=3, fill=-1)

648 >>> a, b, c

649 ((0, 3, 6, 9), (1, 4, 7, -1), (2, 5, 8, -1))

650

651 >>> tuple(splice(list(range(9)), n=5))

652 ([0, 5], [1, 6], [2, 7], [3, 8], [4])

653

654 >>> splice(range(9), n=1)

655 <generator object splice at 0x0...>

656 '''

657 if not isint(n):

658 raise _TypeError(n=n)

659

660 t = iterable

661 if not isinstance(t, _list_tuple_types):

662 t = tuple(t) # force tuple, also for PyPy3

663

664 if n > 1:

665 if fill:

666 fill = _xkwds_get(fill, fill=MISSING)

667 if fill is not MISSING:

668 m = len(t) % n

669 if m > 0: # same type fill

670 t += type(t)((fill,) * (n - m))

671 for i in range(n):

672 # XXX t[i::n] chokes PyChecker

673 yield t[slice(i, None, n)]

674 else:

675 yield t

676

677

678 def _splituple(strs, *sep_splits): # in .mgrs, .osgr, .webmercator

679 '''(INTERNAL) Split a C{comma}- or C{whitespace}-separated

680 string into a C{tuple} of stripped strings.

681 '''

682 t = (strs.split(*sep_splits) if sep_splits else

683 strs.replace(_COMMA_, _SPACE_).split()) if strs else ()

684 return tuple(s.strip() for s in t if s)

685

686

687 def unsigned0(x):

688 '''Unsign if C{0.0}.

689

690 @return: C{B{x}} if B{C{x}} else C{0.0}.

691 '''

692 return x if x else _0_0

693

694

695 def _xcopy(obj, deep=False):

696 '''(INTERNAL) Copy an object, shallow or deep.

697

698 @arg obj: The object to copy (any C{type}).

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

700 a shallow copy (C{bool}).

701

702 @return: The copy of B{C{obj}}.

703 '''

704 return _deepcopy(obj) if deep else _copy(obj)

705

706

707 def _xdup(obj, deep=False, **items):

708 '''(INTERNAL) Duplicate an object, replacing some attributes.

709

710 @arg obj: The object to copy (any C{type}).

711 @kwarg deep: If C{True} copy deep, otherwise shallow.

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

713

714 @return: A duplicate of B{C{obj}} with modified

715 attributes, if any B{C{items}}.

716

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

718 '''

719 d = _xcopy(obj, deep=deep)

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

721 if getattr(d, n, v) != v:

722 setattr(d, n, v)

723 elif not hasattr(d, n):

724 t = _MODS.named.classname(obj)

725 t = _SPACE_(_DOT_(t, n), _invalid_)

726 raise _AttributeError(txt=t, obj=obj, **items)

727# if items:

728# _MODS.props._update_all(d)

729 return d

730

731

732 def _xgeographiclib(where, *required):

733 '''(INTERNAL) Import C{geographiclib} and check required version.

734 '''

735 try:

736 _xpackage(_xgeographiclib)

737 import geographiclib

738 except ImportError as x:

739 raise _xImportError(x, where, Error=LazyImportError)

740 return _xversion(geographiclib, where, *required)

741

742

743 def _xImportError(exc, where, Error=_ImportError, **name):

744 '''(INTERNAL) Embellish an C{Lazy/ImportError}.

745 '''

746 t = _req_d_by(where, **name)

747 return Error(_Xstr(exc), txt=t, cause=exc)

748

749

750 def _xinstanceof(*Types, **names_values):

751 '''(INTERNAL) Check C{Types} of all C{name=value} pairs.

752

753 @arg Types: One or more classes or types (C{class}), all

754 positional.

755 @kwarg names_values: One or more C{B{name}=value} pairs

756 with the C{value} to be checked.

757

758 @raise TypeError: One B{C{names_values}} pair is not an

759 instance of any of the B{C{Types}}.

760 '''

761 if not (Types and names_values):

762 raise _xAssertionError(_xinstanceof, *Types, **names_values)

763

764 for n, v in names_values.items():

765 if not isinstance(v, Types):

766 raise _TypesError(n, v, *Types)

767

768

769 def _xisscalar(**names_values):

770 '''(INTERNAL) Check all C{name=value} pairs to be C{scalar}.

771 '''

772 for n, v in names_values.items():

773 if not isscalar(v):

774 raise _TypeError(n, v, txt=_not_scalar_)

775

776

777 def _xnumpy(where, *required):

778 '''(INTERNAL) Import C{numpy} and check required version.

779 '''

780 try:

781 _xpackage(_xnumpy)

782 import numpy

783 except ImportError as x:

784 raise _xImportError(x, where)

785 return _xversion(numpy, where, *required)

786

787

788 def _xor(x, *xs):

789 '''(INTERNAL) Exclusive-or C{x} and C{xs}.

790 '''

791 for x_ in xs:

792 x ^= x_

793 return x

794

795

796 def _xpackage(_xpkg):

797 '''(INTERNAL) Check dependency to be excluded.

798 '''

799 n = _xpkg.__name__[2:] # remove _x

800 if n in _XPACKAGES:

801 x = _SPACE_(n, _in_, _PYGEODESY_XPACKAGES_)

802 e = _enquote(_getenv(_PYGEODESY_XPACKAGES_, NN))

803 raise ImportError(_EQUAL_(x, e))

804

805

806 def _xscipy(where, *required):

807 '''(INTERNAL) Import C{scipy} and check required version.

808 '''

809 try:

810 _xpackage(_xscipy)

811 import scipy

812 except ImportError as x:

813 raise _xImportError(x, where)

814 return _xversion(scipy, where, *required)

815

816

817 def _xsubclassof(*Classes, **names_values):

818 '''(INTERNAL) Check (super) class of all C{name=value} pairs.

819

820 @arg Classes: One or more classes or types (C{class}), all

821 positional.

822 @kwarg names_values: One or more C{B{name}=value} pairs

823 with the C{value} to be checked.

824

825 @raise TypeError: One B{C{names_values}} pair is not a

826 (sub-)class of any of the B{C{Classes}}.

827 '''

828 if not (Classes and names_values):

829 raise _xAssertionError(_xsubclassof, *Classes, **names_values)

830

831 for n, v in names_values.items():

832 if not issubclassof(v, *Classes):

833 raise _TypesError(n, v, *Classes)

834

835

836 def _xversion(package, where, *required, **name):

837 '''(INTERNAL) Check the C{package} version vs B{C{required}}.

838 '''

839 if required:

840 t = _version_info(package)

841 if t[:len(required)] < required:

842 t = _SPACE_(package.__name__,

843 _version_, _DOT_(*t),

844 _below_, _DOT_(*required),

845 _req_d_by(where, **name))

846 raise ImportError(t)

847 return package

848

849

850 def _xzip(*args, **strict): # PYCHOK no cover

851 '''(INTERNAL) Standard C{zip(..., strict=True)}.

852 '''

853 s = _xkwds_get(strict, strict=True)

854 if s:

855 if _zip is zip: # < (3, 10)

856 t = _MODS.streprs.unstr(_xzip, *args, strict=s)

857 raise _NotImplementedError(t, txt=None)

858 return _zip(*args)

859 return zip(*args)

860

861

862 if _sys_version_info2 < (3, 10): # see .errors

863 _zip = zip # PYCHOK exported

864 else: # Python 3.10+

865

866 def _zip(*args):

867 return zip(*args, strict=True)

868

869_XPACKAGES = _splituple(_getenv(_PYGEODESY_XPACKAGES_, NN).lower())

870

871# **) MIT License

872#

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

874#

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

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

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

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

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

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

881#

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

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

884#

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

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

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

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

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

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

891# OTHER DEALINGS IN THE SOFTWARE.