Coverage for pygeodesy/basics.py: 90%

232 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-10-11 16:04 -0400

1 

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

3 

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

5 

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

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

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

9''' 

10# make sure int/int division yields float quotient 

11from __future__ import division 

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

13if not division: 

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

15del division 

16 

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

18 _TypeError, _TypesError, _ValueError, _xkwds_get 

19from pygeodesy.interns import MISSING, NN, _1_, _by_, _COMMA_, _DOT_, _ELLIPSIS4_, \ 

20 _enquote, _EQUAL_, _in_, _invalid_, _N_A_, _SPACE_, \ 

21 _UNDER_, _version_ # _utf_8_ 

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

23 _getenv, _sys, _sys_version_info2 

24 

25from copy import copy as _copy, deepcopy as _deepcopy 

26from math import copysign as _copysign 

27import inspect as _inspect 

28 

29__all__ = _ALL_LAZY.basics 

30__version__ = '23.10.08' 

31 

32_0_0 = 0.0 # in .constants 

33_below_ = 'below' 

34_can_t_ = "can't" 

35_list_tuple_types = (list, tuple) 

36_list_tuple_set_types = (list, tuple, set) 

37_odd_ = 'odd' 

38_required_ = 'required' 

39_PYGEODESY_XPACKAGES_ = 'PYGEODESY_XPACKAGES' 

40 

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

42 from numbers import Integral as _Ints, Real as _Scalars 

43except 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 

50try: 

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 

60except ImportError: 

61 _Sequence = tuple # immutable for .points._Basequence 

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

63 

64try: 

65 _Bytes = unicode, bytearray # PYCHOK expected 

66 _Strs = basestring, str # XXX , bytes 

67 

68 def _pass(x): # == .utily._passarg 

69 '''Pass thru, no-op''' 

70 return x 

71 

72 str2ub = ub2str = _pass # avoids UnicodeDecodeError 

73 

74 def _Xstr(exc): # PYCHOK no cover 

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

76 

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

78 

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

80 on arm64 Apple Silicon running macOS' Python 2.7.16? 

81 ''' 

82 t = str(exc) 

83 if '_distributor_init' in t: 

84 from sys import exc_info 

85 from traceback import extract_tb 

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

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

88 t = _SPACE_(_can_t_, t4[3] or _N_A_) 

89 del tb, t4 

90 return t 

91 

92except NameError: # Python 3+ 

93 from pygeodesy.interns import _utf_8_ 

94 

95 _Bytes = bytes, bytearray 

96 _Strs = str, # tuple 

97 _Xstr = str 

98 

99 def str2ub(sb): 

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

101 ''' 

102 if isinstance(sb, _Strs): 

103 sb = sb.encode(_utf_8_) 

104 return sb 

105 

106 def ub2str(ub): 

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

108 ''' 

109 if isinstance(ub, _Bytes): 

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

111 return ub 

112 

113 

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

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

116 

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

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

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

120 

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

122 ''' 

123 T = type(sb) 

124 if len(sb) > limit > 8: 

125 h = limit // 2 

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

127 if white: # replace whitespace 

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

129 return sb 

130 

131 

132def copysign0(x, y): 

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

134 

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

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

137 ''' 

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

139 

140 

141def copytype(x, y): 

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

143 

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

145 ''' 

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

147 

148 

149def halfs2(str2): 

150 '''Split a string in 2 halfs. 

151 

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

153 

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

155 

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

157 ''' 

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

159 if r or not h: 

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

161 return str2[:h], str2[h:] 

162 

163 

164def int1s(x): 

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

166 

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

168 ''' 

169 try: 

170 return x.bit_count() # Python 3.10+ 

171 except AttributeError: 

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

173 return bin(x).count(_1_) 

174 

175 

176def isbool(obj): 

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

178 

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

180 

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

182 C{False} otherwise. 

183 ''' 

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

185# or obj is True) 

186 

187if isbool(1) or isbool(0): # PYCHOK assert 

188 raise _AssertionError(isbool=1) 

189 

190if _FOR_DOCS: # XXX avoid epidoc Python 2.7 error 

191 

192 def isclass(obj): 

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

194 

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

196 ''' 

197 return _inspect.isclass(obj) 

198else: 

199 isclass = _inspect.isclass 

200 

201 

202def isCartesian(obj): 

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

204 

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

206 

207 @return: C{type(B{obj}} if B{C{obj}} is a C{Cartesian} 

208 instance, C{None} otherwise. 

209 ''' 

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

211 

212 

213def iscomplex(obj): 

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

215 

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

217 

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

219 C{False}. 

220 ''' 

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

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

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

224 except (TypeError, ValueError): 

225 return False 

226 

227 

228def isfloat(obj): 

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

230 

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

232 

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

234 C{False}. 

235 ''' 

236 try: 

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

238 and isinstance(float(obj), float)) 

239 except (TypeError, ValueError): 

240 return False 

241 

242 

243try: 

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

245except AttributeError: # Python 2- 

246 

247 def isidentifier(obj): 

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

249 ''' 

250 return bool(obj and isstr(obj) 

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

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

253 

254 

255def isinstanceof(obj, *classes): 

256 '''Is B{C{ob}} an intance of one of the C{classes}? 

257 

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

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

260 

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

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

263 ''' 

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

265 

266 

267def isint(obj, both=False): 

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

269 

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

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

272 type and value (C{bool}). 

273 

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

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

276 

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

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

279 ''' 

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

281 return True 

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

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

284 return obj.is_integer() 

285 except AttributeError: 

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

287 return False 

288 

289 

290try: 

291 from keyword import iskeyword # Python 2.7+ 

292except ImportError: 

293 

294 def iskeyword(unused): 

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

296 ''' 

297 return False 

298 

299 

300def isLatLon(obj): 

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

302 

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

304 

305 @return: C{type(B{obj}} if B{C{obj}} is a C{LatLon} 

306 instance, C{None} otherwise. 

307 ''' 

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

309 

310 

311def islistuple(obj, minum=0): 

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

313 

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

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

316 

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

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

319 ''' 

320 return type(obj) in _list_tuple_types and len(obj) >= (minum or 0) 

321 

322 

323def isNvector(obj): 

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

325 

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

327 

328 @return: C{type(B{obj}} if B{C{obj}} is an C{Nvector} 

329 instance, C{None} otherwise. 

330 ''' 

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

332 

333 

334def isodd(x): 

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

336 

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

338 

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

340 C{False} otherwise. 

341 ''' 

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

343 

344 

345def isscalar(obj): 

346 '''Check for scalar types. 

347 

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

349 

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

351 ''' 

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

353 

354 

355def issequence(obj, *excls): 

356 '''Check for sequence types. 

357 

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

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

360 

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

362 

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

364 ''' 

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

366 

367 

368def isstr(obj): 

369 '''Check for string types. 

370 

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

372 

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

374 ''' 

375 return isinstance(obj, _Strs) 

376 

377 

378def issubclassof(Sub, *Supers): 

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

380 

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

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

383 

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

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

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

387 are a class. 

388 ''' 

389 if isclass(Sub): 

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

391 if t: 

392 return bool(issubclass(Sub, t)) 

393 return None 

394 

395 

396def len2(items): 

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

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

399 

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

401 

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

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

404 ''' 

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

406 items = list(items) 

407 return len(items), items 

408 

409 

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

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

412 return a C{tuple} of results. 

413 

414 @arg fun1: 1-Arg function to apply (C{callable}). 

415 @arg xs: Arguments to apply (C{any positional}). 

416 

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

418 ''' 

419 return tuple(map(fun1, xs)) 

420 

421 

422def map2(func, *xs): 

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

424 

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

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

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

428 maintains the Python 2 behavior. 

429 

430 @arg func: Function to apply (C{callable}). 

431 @arg xs: Arguments to apply (C{list, tuple, ...}). 

432 

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

434 ''' 

435 return tuple(map(func, *xs)) 

436 

437 

438def neg(x, neg0=None): 

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

440 

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

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

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

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

445 

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

447 ''' 

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

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

450 

451 

452def neg_(*xs): 

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

454 

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

456 ''' 

457 return map(neg, xs) 

458 

459 

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

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

462 ''' 

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

464 

465 

466def signBit(x): 

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

468 

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

470 ''' 

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

472 

473 

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

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

476 ''' 

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

478 

479 

480def signOf(x): 

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

482 

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

484 ''' 

485 try: 

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

487 except AttributeError: 

488 s = _signOf(x, 0) 

489 return s 

490 

491 

492def _sizeof(inst): 

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

494 

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

496 ignoring class attributes and 

497 counting duplicates only once or 

498 C{None}. 

499 

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

501 ''' 

502 try: 

503 _zB = _sys.getsizeof 

504 _zD = _zB(None) # get some default 

505 except TypeError: # PyPy3.10 

506 return None 

507 

508 def _zR(s, iterable): 

509 z, _s = 0, s.add 

510 for o in iterable: 

511 i = id(o) 

512 if i not in s: 

513 _s(i) 

514 z += _zB(o, _zD) 

515 if isinstance(o, dict): 

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

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

518 elif isinstance(o, _list_tuple_set_types): 

519 z += _zR(s, o) 

520 else: 

521 try: # size instance' attr values only 

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

523 except AttributeError: # None, int, etc. 

524 pass 

525 return z 

526 

527 return _zR(set(), (inst,)) 

528 

529 

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

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

532 

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

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

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

536 

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

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

539 

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

541 

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

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

544 

545 @example: 

546 

547 >>> from pygeodesy import splice 

548 

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

550 >>> a, b 

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

552 

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

554 >>> a, b, c 

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

556 

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

558 >>> a, b, c 

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

560 

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

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

563 

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

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

566 ''' 

567 if not isint(n): 

568 raise _TypeError(n=n) 

569 

570 t = iterable 

571 if not isinstance(t, _list_tuple_types): 

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

573 

574 if n > 1: 

575 if fill: 

576 fill = _xkwds_get(fill, fill=MISSING) 

577 if fill is not MISSING: 

578 m = len(t) % n 

579 if m > 0: # same type fill 

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

581 for i in range(n): 

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

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

584 else: 

585 yield t 

586 

587 

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

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

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

591 ''' 

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

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

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

595 

596 

597_XPACKAGES = _splituple(_getenv(_PYGEODESY_XPACKAGES_, NN)) 

598 

599 

600def unsigned0(x): 

601 '''Unsign if C{0.0}. 

602 

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

604 ''' 

605 return x if x else _0_0 

606 

607 

608def _xargs_names(callabl): 

609 '''(INTERNAL) Get the C{callabl}'s args names. 

610 ''' 

611 try: 

612 args_kwds = _inspect.signature(callabl).parameters.keys() 

613 except AttributeError: # .signature new Python 3+ 

614 args_kwds = _inspect.getargspec(callabl).args 

615 return tuple(args_kwds) 

616 

617 

618def _xcopy(inst, deep=False): 

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

620 

621 @arg inst: The object to copy (any C{type}). 

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

623 a shallow copy (C{bool}). 

624 

625 @return: The copy of B{C{inst}}. 

626 ''' 

627 return _deepcopy(inst) if deep else _copy(inst) 

628 

629 

630def _xdup(inst, deep=False, **items): 

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

632 

633 @arg inst: The object to copy (any C{type}). 

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

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

636 

637 @return: A duplicate of B{C{inst}} with modified 

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

639 

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

641 ''' 

642 d = _xcopy(inst, deep=deep) 

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

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

645 setattr(d, n, v) 

646 elif not hasattr(d, n): 

647 t = _MODS.named.classname(inst) 

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

649 raise _AttributeError(txt=t, this=inst, **items) 

650 return d 

651 

652 

653def _xgeographiclib(where, *required): 

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

655 ''' 

656 try: 

657 _xpackage(_xgeographiclib) 

658 import geographiclib 

659 except ImportError as x: 

660 raise _xImportError(x, where) 

661 return _xversion(geographiclib, where, *required) 

662 

663 

664def _xImportError(x, where, **name): 

665 '''(INTERNAL) Embellish an C{ImportError}. 

666 ''' 

667 t = _SPACE_(_required_, _by_, _xwhere(where, **name)) 

668 return _ImportError(_Xstr(x), txt=t, cause=x) 

669 

670 

671def _xinstanceof(*Types, **name_value_pairs): 

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

673 

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

675 all positional. 

676 @kwarg name_value_pairs: One or more C{B{name}=value} pairs 

677 with the C{value} to be checked. 

678 

679 @raise TypeError: One of the B{C{name_value_pairs}} is not 

680 an instance of any of the B{C{Types}}. 

681 ''' 

682 if Types and name_value_pairs: 

683 for n, v in name_value_pairs.items(): 

684 if not isinstance(v, Types): 

685 raise _TypesError(n, v, *Types) 

686 else: 

687 raise _AssertionError(Types=Types, name_value_pairs=name_value_pairs) 

688 

689 

690def _xnumpy(where, *required): 

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

692 ''' 

693 try: 

694 _xpackage(_xnumpy) 

695 import numpy 

696 except ImportError as x: 

697 raise _xImportError(x, where) 

698 return _xversion(numpy, where, *required) 

699 

700 

701def _xpackage(_xpkg): 

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

703 ''' 

704 n = _xpkg.__name__[2:] 

705 if n in _XPACKAGES: 

706 x = _SPACE_(n, _in_, _PYGEODESY_XPACKAGES_) 

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

708 raise ImportError(_EQUAL_(x, e)) 

709 

710 

711def _xor(x, *xs): 

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

713 ''' 

714 for x_ in xs: 

715 x ^= x_ 

716 return x 

717 

718 

719def _xscipy(where, *required): 

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

721 ''' 

722 try: 

723 _xpackage(_xscipy) 

724 import scipy 

725 except ImportError as x: 

726 raise _xImportError(x, where) 

727 return _xversion(scipy, where, *required) 

728 

729 

730def _xsubclassof(*Classes, **name_value_pairs): 

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

732 

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

734 all positional. 

735 @kwarg name_value_pairs: One or more C{B{name}=value} pairs 

736 with the C{value} to be checked. 

737 

738 @raise TypeError: One of the B{C{name_value_pairs}} is not 

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

740 ''' 

741 for n, v in name_value_pairs.items(): 

742 if not issubclassof(v, *Classes): 

743 raise _TypesError(n, v, *Classes) 

744 

745 

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

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

748 ''' 

749 n = len(required) 

750 if n: 

751 t = _xversion_info(package) 

752 if t[:n] < required: 

753 t = _SPACE_(package.__name__, _version_, _DOT_(*t), 

754 _below_, _DOT_(*required), 

755 _required_, _by_, _xwhere(where, **name)) 

756 raise ImportError(t) 

757 return package 

758 

759 

760def _xversion_info(package): # in .karney 

761 '''(INTERNAL) Get the C{package.__version_info__} as a 2- or 

762 3-tuple C{(major, minor, revision)} if C{int}s. 

763 ''' 

764 try: 

765 t = package.__version_info__ 

766 except AttributeError: 

767 t = package.__version__.strip() 

768 t = t.replace(_DOT_, _SPACE_).split()[:3] 

769 return map2(int, t) 

770 

771 

772def _xwhere(where, **name): 

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

774 ''' 

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

776 if name: 

777 n = _xkwds_get(name, name=NN) 

778 if n: 

779 m = _DOT_(m, n) 

780 return m 

781 

782 

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

784 _zip = zip # PYCHOK exported 

785else: # Python 3.10+ 

786 

787 def _zip(*args): 

788 return zip(*args, strict=True) 

789 

790# **) MIT License 

791# 

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

793# 

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

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

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

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

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

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

800# 

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

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

803# 

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

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

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

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

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

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

810# OTHER DEALINGS IN THE SOFTWARE.