Coverage for pygeodesy/basics.py: 91%

225 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-10-04 12:08 -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.09.28' 

31 

32_0_0 = 0.0 # in .constants 

33_below_ = 'below' 

34_cannot_ = 'cannot' 

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{... "cannot 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_(_cannot_, 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 iscomplex(obj): 

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

204 

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

206 

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

208 C{False}. 

209 ''' 

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

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

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

213 except (TypeError, ValueError): 

214 return False 

215 

216 

217def isfloat(obj): 

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

219 

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

221 

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

223 C{False}. 

224 ''' 

225 try: 

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

227 and isinstance(float(obj), float)) 

228 except (TypeError, ValueError): 

229 return False 

230 

231 

232try: 

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

234except AttributeError: # Python 2- 

235 

236 def isidentifier(obj): 

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

238 ''' 

239 return bool(obj and isstr(obj) 

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

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

242 

243 

244def isinstanceof(obj, *classes): 

245 '''Check an instance of one or several C{classes}. 

246 

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

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

249 

250 @return: C{True} if B{C{obj}} is in instance of 

251 one of the B{C{classes}}. 

252 ''' 

253 return isinstance(obj, classes) 

254 

255 

256def isint(obj, both=False): 

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

258 

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

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

261 type and value (C{bool}). 

262 

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

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

265 

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

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

268 ''' 

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

270 return True 

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

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

273 return obj.is_integer() 

274 except AttributeError: 

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

276 return False 

277 

278 

279try: 

280 from keyword import iskeyword # Python 2.7+ 

281except ImportError: 

282 

283 def iskeyword(unused): 

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

285 ''' 

286 return False 

287 

288 

289def islistuple(obj, minum=0): 

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

291 

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

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

294 

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

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

297 ''' 

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

299 

300 

301def isodd(x): 

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

303 

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

305 

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

307 C{False} otherwise. 

308 ''' 

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

310 

311 

312def isscalar(obj): 

313 '''Check for scalar types. 

314 

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

316 

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

318 ''' 

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

320 

321 

322def issequence(obj, *excls): 

323 '''Check for sequence types. 

324 

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

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

327 

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

329 

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

331 ''' 

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

333 

334 

335def isstr(obj): 

336 '''Check for string types. 

337 

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

339 

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

341 ''' 

342 return isinstance(obj, _Strs) 

343 

344 

345def issubclassof(Sub, *Supers): 

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

347 

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

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

350 

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

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

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

354 are a class. 

355 ''' 

356 if isclass(Sub): 

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

358 if t: 

359 return bool(issubclass(Sub, t)) 

360 return None 

361 

362 

363def len2(items): 

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

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

366 

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

368 

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

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

371 ''' 

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

373 items = list(items) 

374 return len(items), items 

375 

376 

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

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

379 return a C{tuple} of results. 

380 

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

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

383 

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

385 ''' 

386 return tuple(map(fun1, xs)) 

387 

388 

389def map2(func, *xs): 

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

391 

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

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

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

395 maintains the Python 2 behavior. 

396 

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

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

399 

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

401 ''' 

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

403 

404 

405def neg(x, neg0=None): 

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

407 

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

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

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

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

412 

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

414 ''' 

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

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

417 

418 

419def neg_(*xs): 

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

421 

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

423 ''' 

424 return map(neg, xs) 

425 

426 

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

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

429 ''' 

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

431 

432 

433def signBit(x): 

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

435 

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

437 ''' 

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

439 

440 

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

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

443 ''' 

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

445 

446 

447def signOf(x): 

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

449 

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

451 ''' 

452 try: 

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

454 except AttributeError: 

455 s = _signOf(x, 0) 

456 return s 

457 

458 

459def _sizeof(inst): 

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

461 

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

463 ignoring class attributes and 

464 counting duplicates only once or 

465 C{None}. 

466 

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

468 ''' 

469 try: 

470 _zB = _sys.getsizeof 

471 _zD = _zB(None) # get some default 

472 except TypeError: # PyPy3.10 

473 return None 

474 

475 def _zR(s, iterable): 

476 z, _s = 0, s.add 

477 for o in iterable: 

478 i = id(o) 

479 if i not in s: 

480 _s(i) 

481 z += _zB(o, _zD) 

482 if isinstance(o, dict): 

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

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

485 elif isinstance(o, _list_tuple_set_types): 

486 z += _zR(s, o) 

487 else: 

488 try: # size instance' attr values only 

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

490 except AttributeError: # None, int, etc. 

491 pass 

492 return z 

493 

494 return _zR(set(), (inst,)) 

495 

496 

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

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

499 

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

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

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

503 

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

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

506 

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

508 

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

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

511 

512 @example: 

513 

514 >>> from pygeodesy import splice 

515 

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

517 >>> a, b 

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

519 

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

521 >>> a, b, c 

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

523 

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

525 >>> a, b, c 

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

527 

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

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

530 

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

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

533 ''' 

534 if not isint(n): 

535 raise _TypeError(n=n) 

536 

537 t = iterable 

538 if not isinstance(t, _list_tuple_types): 

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

540 

541 if n > 1: 

542 if fill: 

543 fill = _xkwds_get(fill, fill=MISSING) 

544 if fill is not MISSING: 

545 m = len(t) % n 

546 if m > 0: # same type fill 

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

548 for i in range(n): 

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

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

551 else: 

552 yield t 

553 

554 

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

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

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

558 ''' 

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

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

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

562 

563 

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

565 

566 

567def unsigned0(x): 

568 '''Unsign if C{0.0}. 

569 

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

571 ''' 

572 return x if x else _0_0 

573 

574 

575def _xargs_names(callabl): 

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

577 ''' 

578 try: 

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

580 except AttributeError: # .signature new Python 3+ 

581 args_kwds = _inspect.getargspec(callabl).args 

582 return tuple(args_kwds) 

583 

584 

585def _xcopy(inst, deep=False): 

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

587 

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

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

590 a shallow copy (C{bool}). 

591 

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

593 ''' 

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

595 

596 

597def _xdup(inst, **items): 

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

599 

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

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

602 

603 @return: Shallow duplicate of B{C{inst}} with modified 

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

605 

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

607 ''' 

608 d = _xcopy(inst, deep=False) 

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

610 if not hasattr(d, n): 

611 t = _MODS.named.classname(inst) 

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

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

614 setattr(d, n, v) 

615 return d 

616 

617 

618def _xgeographiclib(where, *required): 

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

620 ''' 

621 try: 

622 _xpackage(_xgeographiclib) 

623 import geographiclib 

624 except ImportError as x: 

625 raise _xImportError(x, where) 

626 return _xversion(geographiclib, where, *required) 

627 

628 

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

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

631 ''' 

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

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

634 

635 

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

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

638 

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

640 all positional. 

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

642 with the C{value} to be checked. 

643 

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

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

646 ''' 

647 if Types and name_value_pairs: 

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

649 if not isinstance(v, Types): 

650 raise _TypesError(n, v, *Types) 

651 else: 

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

653 

654 

655def _xnumpy(where, *required): 

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

657 ''' 

658 try: 

659 _xpackage(_xnumpy) 

660 import numpy 

661 except ImportError as x: 

662 raise _xImportError(x, where) 

663 return _xversion(numpy, where, *required) 

664 

665 

666def _xpackage(_xpkg): 

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

668 ''' 

669 n = _xpkg.__name__[2:] 

670 if n in _XPACKAGES: 

671 x = _SPACE_(n, _in_, _PYGEODESY_XPACKAGES_) 

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

673 raise ImportError(_EQUAL_(x, e)) 

674 

675 

676def _xor(x, *xs): 

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

678 ''' 

679 for x_ in xs: 

680 x ^= x_ 

681 return x 

682 

683 

684def _xscipy(where, *required): 

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

686 ''' 

687 try: 

688 _xpackage(_xscipy) 

689 import scipy 

690 except ImportError as x: 

691 raise _xImportError(x, where) 

692 return _xversion(scipy, where, *required) 

693 

694 

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

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

697 

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

699 all positional. 

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

701 with the C{value} to be checked. 

702 

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

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

705 ''' 

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

707 if not issubclassof(v, *Classes): 

708 raise _TypesError(n, v, *Classes) 

709 

710 

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

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

713 ''' 

714 n = len(required) 

715 if n: 

716 t = _xversion_info(package) 

717 if t[:n] < required: 

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

719 _below_, _DOT_(*required), 

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

721 raise ImportError(t) 

722 return package 

723 

724 

725def _xversion_info(package): # in .karney 

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

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

728 ''' 

729 try: 

730 t = package.__version_info__ 

731 except AttributeError: 

732 t = package.__version__.strip() 

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

734 return map2(int, t) 

735 

736 

737def _xwhere(where, **name): 

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

739 ''' 

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

741 if name: 

742 n = _xkwds_get(name, name=NN) 

743 if n: 

744 m = _DOT_(m, n) 

745 return m 

746 

747 

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

749 _zip = zip # PYCHOK exported 

750else: # Python 3.10+ 

751 

752 def _zip(*args): 

753 return zip(*args, strict=True) 

754 

755# **) MIT License 

756# 

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

758# 

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

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

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

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

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

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

765# 

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

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

768# 

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

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

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

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

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

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

775# OTHER DEALINGS IN THE SOFTWARE.