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.cartesianBase import CartesianBase # _MODS

18# from pygeodesy.constants import isneg0, NEG0 # _MODS

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

20 _TypeError, _TypesError, _ValueError, _xAssertionError, \

21 _xkwds_get

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

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

24 _not_, _not_scalar_, _odd_, _SPACE_, _UNDER_, _version_, \

25 _version_info

26# from pygeodesy.latlonBase import LatLonBase # _MODS

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

28 _getenv, LazyImportError, _sys, _sys_version_info2

29# from pygeodesy.named import classname, modulename # _MODS

30# from pygeodesy.nvectorBase import NvectorBase # _MODS

31# from pygeodesy.props import _update_all # _MODS

32

33 from copy import copy as _copy, deepcopy as _deepcopy

34 from math import copysign as _copysign

35 import inspect as _inspect

36

37__all__ = _ALL_LAZY.basics

38__version__ = '24.05.08'

39

40_0_0 = 0.0 # in .constants

41_below_ = 'below'

42_list_tuple_types = (list, tuple)

43_list_tuple_set_types = (list, tuple, set)

44_PYGEODESY_XPACKAGES_ = 'PYGEODESY_XPACKAGES'

45_required_ = 'required'

46

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

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

49 except ImportError:

50 try:

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

52 except NameError: # Python 3+

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

54 _Scalars = _Ints + (float,)

55

56 try:

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

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

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

60 from collections import Sequence as _Sequence # in .points

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

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

63 _Seqs = _Sequence

64 else:

65 raise ImportError() # _AssertionError

66 except ImportError:

67 _Sequence = tuple # immutable for .points._Basequence

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

69

70

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

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

73 '''

74 return arg

75

76

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

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

79 '''

80 return args

81

82

83 try:

84 _Bytes = unicode, bytearray # PYCHOK expected

85 _Strs = basestring, str # XXX , bytes

86 str2ub = ub2str = _passarg # avoids UnicodeDecodeError

87

88 def _Xstr(exc): # PYCHOK no cover

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

90

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

92

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

94 on arm64 Apple Silicon running macOS' Python 2.7.16?

95 '''

96 t = str(exc)

97 if '_distributor_init' in t:

98 from sys import exc_info

99 from traceback import extract_tb

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

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

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

103 del tb, t4

104 return t

105

106 except NameError: # Python 3+

107 from pygeodesy.interns import _utf_8_

108

109 _Bytes = bytes, bytearray

110 _Strs = str, # tuple

111 _Xstr = str

112

113 def str2ub(sb):

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

115 '''

116 if isinstance(sb, _Strs):

117 sb = sb.encode(_utf_8_)

118 return sb

119

120 def ub2str(ub):

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

122 '''

123 if isinstance(ub, _Bytes):

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

125 return ub

126

127

128 def _args_kwds_names(func):

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

130 C{self} for methods.

131

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

133 C{**kwds} names.

134 '''

135 try:

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

137 except AttributeError: # .signature new Python 3+

138 args_kwds = _inspect.getargspec(func).args

139 return tuple(args_kwds)

140

141

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

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

144

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

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

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

148

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

150 '''

151 T = type(sb)

152 if len(sb) > limit > 8:

153 h = limit // 2

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

155 if white: # replace whitespace

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

157 return sb

158

159

160 def copysign0(x, y):

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

162

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

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

165 '''

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

167

168

169 def copytype(x, y):

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

171

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

173 '''

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

175

176

177 def halfs2(str2):

178 '''Split a string in 2 halfs.

179

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

181

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

183

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

185 '''

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

187 if r or not h:

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

189 return str2[:h], str2[h:]

190

191

192 def int1s(x):

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

194

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

196 '''

197 try:

198 return x.bit_count() # Python 3.10+

199 except AttributeError:

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

201 return bin(x).count(_1_)

202

203

204 def isbool(obj):

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

206

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

208

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

210 C{False} otherwise.

211 '''

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

213# or obj is True)

214

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

216

217 if _FOR_DOCS: # XXX avoid epydoc Python 2.7 error

218

219 def isclass(obj):

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

221

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

223 '''

224 return _inspect.isclass(obj)

225 else:

226 isclass = _inspect.isclass

227

228

229 def isCartesian(obj, ellipsoidal=None):

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

231

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

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

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

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

236

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

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

239 type or C{None} otherwise.

240 '''

241 if ellipsoidal is not None:

242 try:

243 return obj.ellipsoidalCartesian if ellipsoidal else obj.sphericalCartesian

244 except AttributeError:

245 return None

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

247

248

249 def iscomplex(obj):

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

251

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

253

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

255 C{False}.

256 '''

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

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

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

260 except (TypeError, ValueError):

261 return False

262

263

264 def isDEPRECATED(obj):

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

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

267 '''

268 try: # XXX inspect.getdoc(obj)

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

270 except AttributeError:

271 return None

272

273

274 def isfloat(obj):

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

276

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

278

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

280 C{False}.

281 '''

282 try:

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

284 and isinstance(float(obj), float))

285 except (TypeError, ValueError):

286 return False

287

288

289 try:

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

291 except AttributeError: # Python 2-

292

293 def isidentifier(obj):

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

295 '''

296 return bool(obj and isstr(obj)

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

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

299

300

301 def isinstanceof(obj, *classes):

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

303

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

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

306

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

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

309 '''

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

311

312

313 def isint(obj, both=False):

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

315

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

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

318 type and value (C{bool}).

319

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

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

322

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

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

325 '''

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

327 return True

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

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

330 return obj.is_integer()

331 except AttributeError:

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

333 return False

334

335

336 try:

337 from keyword import iskeyword # Python 2.7+

338 except ImportError:

339

340 def iskeyword(unused):

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

342 '''

343 return False

344

345

346 def isLatLon(obj, ellipsoidal=None):

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

348

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

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

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

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

353

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

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

356 type or {None} otherwise.

357 '''

358 if ellipsoidal is not None:

359 try:

360 return obj.ellipsoidalLatLon if ellipsoidal else obj.sphericalLatLon

361 except AttributeError:

362 return None

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

364

365

366 def islistuple(obj, minum=0):

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

368

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

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

371

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

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

374 '''

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

376

377

378 def isNvector(obj, ellipsoidal=None):

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

380

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

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

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

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

385

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

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

388 type or {None} otherwise.

389 '''

390 if ellipsoidal is not None:

391 try:

392 return obj.ellipsoidalNvector if ellipsoidal else obj.sphericalNvector

393 except AttributeError:

394 return None

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

396

397

398 def isodd(x):

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

400

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

402

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

404 C{False} otherwise.

405 '''

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

407

408

409 def isscalar(obj):

410 '''Check for scalar types.

411

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

413

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

415 '''

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

417

418

419 def issequence(obj, *excls):

420 '''Check for sequence types.

421

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

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

424

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

426

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

428 '''

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

430

431

432 def isstr(obj):

433 '''Check for string types.

434

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

436

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

438 '''

439 return isinstance(obj, _Strs)

440

441

442 def issubclassof(Sub, *Supers):

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

444

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

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

447

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

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

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

451 are a class.

452 '''

453 if isclass(Sub):

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

455 if t:

456 return bool(issubclass(Sub, t))

457 return None

458

459

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

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

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

463

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

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

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

467 for I{alphabetical, case-sensitive} sorting and

468 C{B{reverse}=True} for sorting in C{descending}

469 order.

470 '''

471 def _ins(item):

472 return item[0].lower()

473

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

475 return (_ins if asorted else None), reverse

476

477 key, rev = _key_rev(**asorted_reverse)

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

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

480

481

482 def len2(items):

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

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

485

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

487

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

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

490 '''

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

492 items = list(items)

493 return len(items), items

494

495

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

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

498 return a C{tuple} of results.

499

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

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

502

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

504 '''

505 return tuple(map(fun1, xs))

506

507

508 def map2(fun, *xs):

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

510

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

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

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

514 maintains the Python 2 behavior.

515

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

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

518

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

520 '''

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

522

523

524 def neg(x, neg0=None):

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

526

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

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

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

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

531

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

533 '''

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

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

536

537

538 def neg_(*xs):

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

540

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

542 '''

543 return map(neg, xs)

544

545

546 def _neg0(x):

547 '''(INTERNAL) Return C{NEG0 if x < 0 else _0_0},

548 unlike C{_copysign_0_0} which returns C{_N_0_0}.

549 '''

550 return _MODS.constants.NEG0 if x < 0 else _0_0

551

552

553 def _req_d_by(where, name=NN): # in .basics

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

555 '''

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

557 if name:

558 m = _DOT_(m, name)

559 return _SPACE_(_required_, _by_, m)

560

561

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

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

564 '''

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

566

567

568 def signBit(x):

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

570

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

572 '''

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

574

575

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

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

578 '''

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

580

581

582 def signOf(x):

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

584

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

586 '''

587 try:

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

589 except AttributeError:

590 s = _signOf(x, 0)

591 return s

592

593

594 def _sizeof(inst):

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

596

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

598 ignoring class attributes and

599 counting duplicates only once or

600 C{None}.

601

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

603 '''

604 try:

605 _zB = _sys.getsizeof

606 _zD = _zB(None) # get some default

607 except TypeError: # PyPy3.10

608 return None

609

610 def _zR(s, iterable):

611 z, _s = 0, s.add

612 for o in iterable:

613 i = id(o)

614 if i not in s:

615 _s(i)

616 z += _zB(o, _zD)

617 if isinstance(o, dict):

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

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

620 elif isinstance(o, _list_tuple_set_types):

621 z += _zR(s, o)

622 else:

623 try: # size instance' attr values only

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

625 except AttributeError: # None, int, etc.

626 pass

627 return z

628

629 return _zR(set(), (inst,))

630

631

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

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

634

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

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

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

638

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

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

641

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

643

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

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

646

647 @example:

648

649 >>> from pygeodesy import splice

650

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

652 >>> a, b

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

654

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

656 >>> a, b, c

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

658

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

660 >>> a, b, c

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

662

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

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

665

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

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

668 '''

669 if not isint(n):

670 raise _TypeError(n=n)

671

672 t = iterable

673 if not isinstance(t, _list_tuple_types):

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

675

676 if n > 1:

677 if fill:

678 fill = _xkwds_get(fill, fill=MISSING)

679 if fill is not MISSING:

680 m = len(t) % n

681 if m > 0: # same type fill

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

683 for i in range(n):

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

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

686 else:

687 yield t

688

689

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

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

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

693 '''

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

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

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

697

698

699 def unsigned0(x):

700 '''Unsign if C{0.0}.

701

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

703 '''

704 return x if x else _0_0

705

706

707 def _xcopy(obj, deep=False):

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

709

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

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

712 a shallow copy (C{bool}).

713

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

715 '''

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

717

718

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

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

721

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

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

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

725

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

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

728

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

730 '''

731 d = _xcopy(obj, deep=deep)

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

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

734 setattr(d, n, v)

735 elif not hasattr(d, n):

736 t = _MODS.named.classname(obj)

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

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

739# if items:

740# _MODS.props._update_all(d)

741 return d

742

743

744 def _xgeographiclib(where, *required):

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

746 '''

747 try:

748 _xpackage(_xgeographiclib)

749 import geographiclib

750 except ImportError as x:

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

752 return _xversion(geographiclib, where, *required)

753

754

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

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

757 '''

758 t = _req_d_by(where, **name)

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

760

761

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

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

764

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

766 positional.

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

768 with the C{value} to be checked.

769

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

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

772 '''

773 if not (Types and names_values):

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

775

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

777 if not isinstance(v, Types):

778 raise _TypesError(n, v, *Types)

779

780

781 def _xisscalar(**names_values):

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

783 '''

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

785 if not isscalar(v):

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

787

788

789 def _xiterable(obj):

790 '''(INTERNAL) Raise C{TypeError} if C{obj} is not iterable.

791 '''

792 # https://PyPI.org/project/isiterable/

793 if not (hasattr(obj, '__iter__') or

794 hasattr(obj, '__getitem__')):

795 raise TypeError(_not_(_xiterable.__name__[2:]))

796

797

798 def _xnumpy(where, *required):

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

800 '''

801 try:

802 _xpackage(_xnumpy)

803 import numpy

804 except ImportError as x:

805 raise _xImportError(x, where)

806 return _xversion(numpy, where, *required)

807

808

809 def _xor(x, *xs):

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

811 '''

812 for x_ in xs:

813 x ^= x_

814 return x

815

816

817 def _xpackage(_xpkg):

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

819 '''

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

821 if n in _XPACKAGES:

822 x = _SPACE_(n, _in_, _PYGEODESY_XPACKAGES_)

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

824 raise ImportError(_EQUAL_(x, e))

825

826

827 def _xscipy(where, *required):

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

829 '''

830 try:

831 _xpackage(_xscipy)

832 import scipy

833 except ImportError as x:

834 raise _xImportError(x, where)

835 return _xversion(scipy, where, *required)

836

837

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

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

840

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

842 positional.

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

844 with the C{value} to be checked.

845

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

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

848 '''

849 if not (Classes and names_values):

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

851

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

853 if not issubclassof(v, *Classes):

854 raise _TypesError(n, v, *Classes)

855

856

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

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

859 '''

860 if required:

861 t = _version_info(package)

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

863 t = _SPACE_(package.__name__,

864 _version_, _DOT_(*t),

865 _below_, _DOT_(*required),

866 _req_d_by(where, **name))

867 raise ImportError(t)

868 return package

869

870

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

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

873 '''

874 s = _xkwds_get(strict, strict=True)

875 if s:

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

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

878 raise _NotImplementedError(t, txt=None)

879 return _zip(*args)

880 return zip(*args)

881

882

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

884 _zip = zip # PYCHOK exported

885 else: # Python 3.10+

886

887 def _zip(*args):

888 return zip(*args, strict=True)

889

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

891

892# **) MIT License

893#

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

895#

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

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

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

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

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

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

902#

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

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

905#

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

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

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

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

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

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

912# OTHER DEALINGS IN THE SOFTWARE.