Coverage for pygeodesy/basics.py: 95%
252 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-03-03 11:31 -0500
« prev ^ index » next coverage.py v7.2.2, created at 2024-03-03 11:31 -0500
2# -*- coding: utf-8 -*-
4u'''Some, basic definitions, functions and dependencies.
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
17from pygeodesy.errors import _AttributeError, _ImportError, _NotImplementedError, \
18 _TypeError, _TypesError, _ValueError, _xAssertionError, \
19 _xkwds_get
20from 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
23from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, _FOR_DOCS, \
24 _getenv, LazyImportError, _sys, _sys_version_info2
26from copy import copy as _copy, deepcopy as _deepcopy
27from math import copysign as _copysign
28import inspect as _inspect
30__all__ = _ALL_LAZY.basics
31__version__ = '24.02.21'
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'
41try: # Luciano Ramalho, "Fluent Python", O'Reilly, 2016 p. 395, 2022 p. 577+
42 from numbers import Integral as _Ints, Real as _Scalars # .units
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,)
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
65def _passarg(arg): # in .auxilats.auxLat
66 '''(INTERNAL) Helper, no-op.
67 '''
68 return arg
71def _passargs(*args): # in .utily
72 '''(INTERNAL) Helper, no-op.
73 '''
74 return args
77try:
78 _Bytes = unicode, bytearray # PYCHOK expected
79 _Strs = basestring, str # XXX , bytes
80 str2ub = ub2str = _passarg # avoids UnicodeDecodeError
82 def _Xstr(exc): # PYCHOK no cover
83 '''I{Invoke only with caught ImportError} B{C{exc}}.
85 C{... "can't import name _distributor_init" ...}
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
100except NameError: # Python 3+
101 from pygeodesy.interns import _utf_8_
103 _Bytes = bytes, bytearray
104 _Strs = str, # tuple
105 _Xstr = str
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
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
122def _args_kwds_names(func):
123 '''(INTERNAL) Get a C{func}'s args and kwds names, including
124 C{self} for methods.
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)
136def clips(sb, limit=50, white=NN):
137 '''Clip a string to the given length limit.
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}).
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
154def copysign0(x, y):
155 '''Like C{math.copysign(x, y)} except C{zero}, I{unsigned}.
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)
163def copytype(x, y):
164 '''Return the value of B{x} as C{type} of C{y}.
166 @return: C{type(B{y})(B{x})}.
167 '''
168 return type(y)(x if x else _0_0)
171def halfs2(str2):
172 '''Split a string in 2 halfs.
174 @arg str2: String to split (C{str}).
176 @return: 2-Tuple C{(_1st, _2nd)} half (C{str}).
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:]
186def int1s(x):
187 '''Count the number of 1-bits in an C{int}, I{unsigned}.
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_)
198def isbool(obj):
199 '''Check whether an object is C{bool}ean.
201 @arg obj: The object (any C{type}).
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)
209assert not (isbool(1) or isbool(0) or isbool(None)) # PYCHOK 2
211if _FOR_DOCS: # XXX avoid epydoc Python 2.7 error
213 def isclass(obj):
214 '''Return C{True} if B{C{obj}} is a C{class} or C{type}.
216 @see: Python's C{inspect.isclass}.
217 '''
218 return _inspect.isclass(obj)
219else:
220 isclass = _inspect.isclass
223def isCartesian(obj, ellipsoidal=None):
224 '''Is B{C{obj}} some C{Cartesian}?
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}.
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)
243def iscomplex(obj):
244 '''Check whether an object is a C{complex} or complex C{str}.
246 @arg obj: The object (any C{type}).
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
258def 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
268def isfloat(obj):
269 '''Check whether an object is a C{float} or float C{str}.
271 @arg obj: The object (any C{type}).
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
283try:
284 isidentifier = str.isidentifier # Python 3, must be str
285except AttributeError: # Python 2-
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())
295def isinstanceof(obj, *classes):
296 '''Is B{C{ob}} an instance of one of the C{classes}?
298 @arg obj: The instance (any C{type}).
299 @arg classes: One or more classes (C{class}).
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
307def isint(obj, both=False):
308 '''Check for C{int} type or an integer C{float} value.
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}).
314 @return: C{True} if B{C{obj}} is C{int} or I{integer}
315 C{float} or L{Fsum}, C{False} otherwise.
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
330try:
331 from keyword import iskeyword # Python 2.7+
332except ImportError:
334 def iskeyword(unused):
335 '''Not Implemented, C{False} always.
336 '''
337 return False
340def isLatLon(obj, ellipsoidal=None):
341 '''Is B{C{obj}} some C{LatLon}?
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}.
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)
360def islistuple(obj, minum=0):
361 '''Check for list or tuple C{type} with a minumal length.
363 @arg obj: The object (any C{type}).
364 @kwarg minum: Minimal C{len} required C({int}).
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
372def isNvector(obj, ellipsoidal=None):
373 '''Is B{C{obj}} some C{Nvector}?
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}.
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)
392def isodd(x):
393 '''Is B{C{x}} odd?
395 @arg x: Value (C{scalar}).
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)
403def isscalar(obj):
404 '''Check for scalar types.
406 @arg obj: The object (any C{type}).
408 @return: C{True} if B{C{obj}} is C{scalar}, C{False} otherwise.
409 '''
410 return isinstance(obj, _Scalars) and not isbool(obj)
413def issequence(obj, *excls):
414 '''Check for sequence types.
416 @arg obj: The object (any C{type}).
417 @arg excls: Classes to exclude (C{type}), all positional.
419 @note: Excluding C{tuple} implies excluding C{namedtuple}.
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))
426def isstr(obj):
427 '''Check for string types.
429 @arg obj: The object (any C{type}).
431 @return: C{True} if B{C{obj}} is C{str}, C{False} otherwise.
432 '''
433 return isinstance(obj, _Strs)
436def issubclassof(Sub, *Supers):
437 '''Check whether a class is a sub-class of some other class(es).
439 @arg Sub: The sub-class (C{class}).
440 @arg Supers: One or more C(super) classes (C{class}).
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
454def 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.
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()
467 def _key_rev(asorted=True, reverse=False):
468 return (_ins if asorted else None), reverse
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)
475def len2(items):
476 '''Make built-in function L{len} work for generators, iterators,
477 etc. since those can only be started exactly once.
479 @arg items: Generator, iterator, list, range, tuple, etc.
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
489def map1(fun1, *xs): # XXX map_
490 '''Apply a single-argument function to each B{C{xs}} and
491 return a C{tuple} of results.
493 @arg fun1: 1-Arg function (C{callable}).
494 @arg xs: Arguments (C{any positional}).
496 @return: Function results (C{tuple}).
497 '''
498 return tuple(map(fun1, xs))
501def map2(fun, *xs):
502 '''Apply a function to arguments and return a C{tuple} of results.
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.
509 @arg fun: Function (C{callable}).
510 @arg xs: Arguments (C{list, tuple, ...}).
512 @return: Function results (C{tuple}).
513 '''
514 return tuple(map(fun, *xs))
517def neg(x, neg0=None):
518 '''Negate C{x} and optionally, negate C{0.0} and C{-0.0}.
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}).
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)))
531def neg_(*xs):
532 '''Negate all C{xs} with L{neg}.
534 @return: A C{map(neg, B{xs})}.
535 '''
536 return map(neg, xs)
539def _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)
550def _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)
556def signBit(x):
557 '''Return C{signbit(B{x})}, like C++.
559 @return: C{True} if C{B{x} < 0} or C{NEG0} (C{bool}).
560 '''
561 return x < 0 or _MODS.constants.isneg0(x)
564def _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)
570def signOf(x):
571 '''Return sign of C{x} as C{int}.
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
582def _sizeof(inst):
583 '''(INTERNAL) Recursively size an C{inst}ance.
585 @return: Instance' size in bytes (C{int}),
586 ignoring class attributes and
587 counting duplicates only once or
588 C{None}.
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
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
617 return _zR(set(), (inst,))
620def splice(iterable, n=2, **fill):
621 '''Split an iterable into C{n} slices.
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.
627 @return: A generator for each of B{C{n}} slices,
628 M{iterable[i::n] for i=0..n}.
630 @raise TypeError: Invalid B{C{n}}.
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}.
635 @example:
637 >>> from pygeodesy import splice
639 >>> a, b = splice(range(10))
640 >>> a, b
641 ((0, 2, 4, 6, 8), (1, 3, 5, 7, 9))
643 >>> a, b, c = splice(range(10), n=3)
644 >>> a, b, c
645 ((0, 3, 6, 9), (1, 4, 7), (2, 5, 8))
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))
651 >>> tuple(splice(list(range(9)), n=5))
652 ([0, 5], [1, 6], [2, 7], [3, 8], [4])
654 >>> splice(range(9), n=1)
655 <generator object splice at 0x0...>
656 '''
657 if not isint(n):
658 raise _TypeError(n=n)
660 t = iterable
661 if not isinstance(t, _list_tuple_types):
662 t = tuple(t) # force tuple, also for PyPy3
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
678def _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)
687def unsigned0(x):
688 '''Unsign if C{0.0}.
690 @return: C{B{x}} if B{C{x}} else C{0.0}.
691 '''
692 return x if x else _0_0
695def _xcopy(obj, deep=False):
696 '''(INTERNAL) Copy an object, shallow or deep.
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}).
702 @return: The copy of B{C{obj}}.
703 '''
704 return _deepcopy(obj) if deep else _copy(obj)
707def _xdup(obj, deep=False, **items):
708 '''(INTERNAL) Duplicate an object, replacing some attributes.
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}).
714 @return: A duplicate of B{C{obj}} with modified
715 attributes, if any B{C{items}}.
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
732def _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)
743def _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)
750def _xinstanceof(*Types, **names_values):
751 '''(INTERNAL) Check C{Types} of all C{name=value} pairs.
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.
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)
764 for n, v in names_values.items():
765 if not isinstance(v, Types):
766 raise _TypesError(n, v, *Types)
769def _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_)
777def _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)
788def _xor(x, *xs):
789 '''(INTERNAL) Exclusive-or C{x} and C{xs}.
790 '''
791 for x_ in xs:
792 x ^= x_
793 return x
796def _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))
806def _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)
817def _xsubclassof(*Classes, **names_values):
818 '''(INTERNAL) Check (super) class of all C{name=value} pairs.
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.
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)
831 for n, v in names_values.items():
832 if not issubclassof(v, *Classes):
833 raise _TypesError(n, v, *Classes)
836def _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
850def _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)
862if _sys_version_info2 < (3, 10): # see .errors
863 _zip = zip # PYCHOK exported
864else: # Python 3.10+
866 def _zip(*args):
867 return zip(*args, strict=True)
869_XPACKAGES = _splituple(_getenv(_PYGEODESY_XPACKAGES_, NN).lower())
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.