Coverage for pygeodesy/basics.py: 95%
244 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-05-25 12:04 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-05-25 12:04 -0400
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
17# from pygeodesy.cartesianBase import CartesianBase # _MODS
18# from pygeodesy.constants import isneg0, NEG0 # _MODS
19from pygeodesy.errors import _AttributeError, _ImportError, _NotImplementedError, \
20 _TypeError, _TypesError, _ValueError, _xAssertionError, \
21 _xkwds_get
22from pygeodesy.internals import _0_0, _enquote, _passarg, _version_info
23from pygeodesy.interns import MISSING, NN, _1_, _by_, _COMMA_, _DOT_, _DEPRECATED_, \
24 _ELLIPSIS4_, _EQUAL_, _in_, _invalid_, _N_A_, _not_, \
25 _not_scalar_, _odd_, _SPACE_, _UNDER_, _version_
26# from pygeodesy.latlonBase import LatLonBase # _MODS
27from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, _FOR_DOCS, _getenv, \
28 LazyImportError, _sys_version_info2
29# from pygeodesy.named import classname, modulename, _name__ # _MODS
30# from pygeodesy.nvectorBase import NvectorBase # _MODS
31# from pygeodesy.props import _update_all # _MODS
32# from pygeodesy.streprs import Fmt # _MODS
34from copy import copy as _copy, deepcopy as _deepcopy
35from math import copysign as _copysign
36import inspect as _inspect
38__all__ = _ALL_LAZY.basics
39__version__ = '24.05.21'
41_below_ = 'below'
42_list_tuple_types = (list, tuple)
43_PYGEODESY_XPACKAGES_ = 'PYGEODESY_XPACKAGES'
44_required_ = 'required'
46try: # Luciano Ramalho, "Fluent Python", O'Reilly, 2016 p. 395, 2022 p. 577+
47 from numbers import Integral as _Ints, Real as _Scalars # .units
48except ImportError:
49 try:
50 _Ints = int, long # int objects (C{tuple})
51 except NameError: # Python 3+
52 _Ints = int, # int objects (C{tuple})
53 _Scalars = (float,) + _Ints
55try:
56 try: # use C{from collections.abc import ...} in Python 3.9+
57 from collections.abc import Sequence as _Sequence # in .points
58 except ImportError: # no .abc in Python 3.8- and 2.7-
59 from collections import Sequence as _Sequence # in .points
60 if isinstance([], _Sequence) and isinstance((), _Sequence):
61 # and isinstance(range(1), _Sequence):
62 _Seqs = _Sequence
63 else:
64 raise ImportError() # _AssertionError
65except ImportError:
66 _Sequence = tuple # immutable for .points._Basequence
67 _Seqs = list, _Sequence # range for function len2 below
69try:
70 _Bytes = unicode, bytearray # PYCHOK expected
71 _Strs = basestring, str # XXX , bytes
72 str2ub = ub2str = _passarg # avoids UnicodeDecodeError
74 def _Xstr(exc): # PYCHOK no cover
75 '''I{Invoke only with caught ImportError} B{C{exc}}.
77 C{... "can't import name _distributor_init" ...}
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
92except NameError: # Python 3+
93 from pygeodesy.interns import _utf_8_
95 _Bytes = bytes, bytearray
96 _Strs = str, # tuple
97 _Xstr = str
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
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
114def _args_kwds_names(func):
115 '''(INTERNAL) Get a C{func}'s args and kwds names, including
116 C{self} for methods.
118 @note: Python 2 may I{not} include the C{*args} nor the
119 C{**kwds} names.
120 '''
121 try:
122 args_kwds = _inspect.signature(func).parameters.keys()
123 except AttributeError: # .signature new Python 3+
124 args_kwds = _inspect.getargspec(func).args
125 return tuple(args_kwds)
128def clips(sb, limit=50, white=NN):
129 '''Clip a string to the given length limit.
131 @arg sb: String (C{str} or C{bytes}).
132 @kwarg limit: Length limit (C{int}).
133 @kwarg white: Optionally, replace all whitespace (C{str}).
135 @return: The clipped or unclipped B{C{sb}}.
136 '''
137 T = type(sb)
138 if len(sb) > limit > 8:
139 h = limit // 2
140 sb = T(_ELLIPSIS4_).join((sb[:h], sb[-h:]))
141 if white: # replace whitespace
142 sb = T(white).join(sb.split())
143 return sb
146def copysign0(x, y):
147 '''Like C{math.copysign(x, y)} except C{zero}, I{unsigned}.
149 @return: C{math.copysign(B{x}, B{y})} if B{C{x}} else
150 C{type(B{x})(0)}.
151 '''
152 return _copysign(x, (y if y else 0)) if x else copytype(0, x)
155def copytype(x, y):
156 '''Return the value of B{x} as C{type} of C{y}.
158 @return: C{type(B{y})(B{x})}.
159 '''
160 return type(y)(x if x else _0_0)
163def halfs2(str2):
164 '''Split a string in 2 halfs.
166 @arg str2: String to split (C{str}).
168 @return: 2-Tuple C{(_1st, _2nd)} half (C{str}).
170 @raise ValueError: Zero or odd C{len(B{str2})}.
171 '''
172 h, r = divmod(len(str2), 2)
173 if r or not h:
174 raise _ValueError(str2=str2, txt=_odd_)
175 return str2[:h], str2[h:]
178def int1s(x):
179 '''Count the number of 1-bits in an C{int}, I{unsigned}.
181 @note: C{int1s(-B{x}) == int1s(abs(B{x}))}.
182 '''
183 try:
184 return x.bit_count() # Python 3.10+
185 except AttributeError:
186 # bin(-x) = '-' + bin(abs(x))
187 return bin(x).count(_1_)
190def isbool(obj):
191 '''Is B{C{obj}}ect a C{bool}ean?
193 @arg obj: The object (any C{type}).
195 @return: C{True} if C{bool}ean, C{False} otherwise.
196 '''
197 return isinstance(obj, bool) # and (obj is False
198# or obj is True)
200assert not (isbool(1) or isbool(0) or isbool(None)) # PYCHOK 2
203def isCartesian(obj, ellipsoidal=None):
204 '''Is B{C{obj}}ect some C{Cartesian}?
206 @arg obj: The object (any C{type}).
207 @kwarg ellipsoidal: If C{None}, return the type of any C{Cartesian},
208 if C{True}, only an ellipsoidal C{Cartesian type}
209 or if C{False}, only a spherical C{Cartesian type}.
211 @return: C{type(B{obj}} if a C{Cartesian} of the required type, C{False}
212 if a C{Cartesian} of an other type or {None} otherwise.
213 '''
214 if ellipsoidal is not None:
215 try:
216 return obj.ellipsoidalCartesian if ellipsoidal else obj.sphericalCartesian
217 except AttributeError:
218 return None
219 return isinstanceof(obj, _MODS.cartesianBase.CartesianBase)
222if _FOR_DOCS: # XXX avoid epydoc Python 2.7 error
224 def isclass(obj):
225 '''Is B{C{obj}}ect a C{Class} or C{type}?
226 '''
227 return _inspect.isclass(obj)
228else:
229 isclass = _inspect.isclass
232def iscomplex(obj, both=False):
233 '''Is B{C{obj}}ect a C{complex} or complex literal C{str}?
235 @arg obj: The object (any C{type}).
236 @kwarg both: If C{True}, check complex C{str} (C{bool}).
238 @return: C{True} if C{complex}, C{False} otherwise.
239 '''
240 try: # hasattr('conjugate', 'real' and 'imag')
241 return isinstance(obj, complex) or bool(both and isstr(obj) and
242 isinstance(complex(obj), complex)) # numbers.Complex?
243 except (TypeError, ValueError):
244 return False
247def isDEPRECATED(obj):
248 '''Is B{C{obj}}ect a C{DEPRECATED} class, method or function?
250 @return: C{True} if C{DEPRECATED}, {False} if not or
251 C{None} if undetermined.
252 '''
253 try: # XXX inspect.getdoc(obj) or obj.__doc__
254 doc = obj.__doc__.lstrip()
255 return bool(doc and doc.startswith(_DEPRECATED_))
256 except AttributeError:
257 return None
260def isfloat(obj, both=False):
261 '''Is B{C{obj}}ect a C{float} or float literal C{str}?
263 @arg obj: The object (any C{type}).
264 @kwarg both: If C{True}, check float C{str} (C{bool}).
266 @return: C{True} if C{float}, C{False} otherwise.
267 '''
268 try:
269 return isinstance(obj, float) or bool(both and
270 isstr(obj) and isinstance(float(obj), float))
271 except (TypeError, ValueError):
272 return False
275try:
276 isidentifier = str.isidentifier # Python 3, must be str
277except AttributeError: # Python 2-
279 def isidentifier(obj):
280 '''Is B{C{obj}}ect a Python identifier?
281 '''
282 return bool(obj and isstr(obj)
283 and obj.replace(_UNDER_, NN).isalnum()
284 and not obj[:1].isdigit())
287def isinstanceof(obj, *Classes):
288 '''Is B{C{obj}}ect an instance of one of the C{Classes}?
290 @arg obj: The object (any C{type}).
291 @arg Classes: One or more classes (C{Class}).
293 @return: C{type(B{obj}} if one of the B{C{Classes}},
294 C{None} otherwise.
295 '''
296 return type(obj) if isinstance(obj, Classes) else None
299def isint(obj, both=False):
300 '''Is B{C{obj}}ect an C{int} or integer C{float} value?
302 @arg obj: The object (any C{type}).
303 @kwarg both: If C{True}, check C{float} and L{Fsum}
304 type and value (C{bool}).
306 @return: C{True} if C{int} or I{integer} C{float}
307 or L{Fsum}, C{False} otherwise.
309 @note: Both C{isint(True)} and C{isint(False)} return
310 C{False} (and no longer C{True}).
311 '''
312 if isinstance(obj, _Ints):
313 return not isbool(obj)
314 elif both: # and isinstance(obj, (float, Fsum))
315 try: # NOT , _Scalars) to include Fsum!
316 return obj.is_integer()
317 except AttributeError:
318 pass # XXX float(int(obj)) == obj?
319 return False
322def isiterable(obj):
323 '''Is B{C{obj}}ect C{iterable}?
325 @arg obj: The object (any C{type}).
327 @return: C{True} if C{iterable}, C{False} otherwise.
328 '''
329 # <https://PyPI.org/project/isiterable/>
330 return hasattr(obj, '__iter__') # map, range, set
333def isiterablen(obj):
334 '''Is B{C{obj}}ect C{iterable} and has C{len}gth?
336 @arg obj: The object (any C{type}).
338 @return: C{True} if C{iterable} with C{len}gth, C{False} otherwise.
339 '''
340 return hasattr(obj, '__len__') and hasattr(obj, '__getitem__')
343try:
344 from keyword import iskeyword # Python 2.7+
345except ImportError:
347 def iskeyword(unused):
348 '''Not Implemented, C{False} always.
349 '''
350 return False
353def isLatLon(obj, ellipsoidal=None):
354 '''Is B{C{obj}}ect some C{LatLon}?
356 @arg obj: The object (any C{type}).
357 @kwarg ellipsoidal: If C{None}, return the type of any C{LatLon},
358 if C{True}, only an ellipsoidal C{LatLon type}
359 or if C{False}, only a spherical C{LatLon type}.
361 @return: C{type(B{obj}} if a C{LatLon} of the required type, C{False}
362 if a C{LatLon} of an other type or {None} otherwise.
363 '''
364 if ellipsoidal is not None:
365 try:
366 return obj.ellipsoidalLatLon if ellipsoidal else obj.sphericalLatLon
367 except AttributeError:
368 return None
369 return isinstanceof(obj, _MODS.latlonBase.LatLonBase)
372def islistuple(obj, minum=0):
373 '''Is B{C{obj}}ect a C{list} or C{tuple} with non-zero length?
375 @arg obj: The object (any C{type}).
376 @kwarg minum: Minimal C{len} required C({int}).
378 @return: C{True} if a C{list} or C{tuple} with C{len} at
379 least B{C{minum}}, C{False} otherwise.
380 '''
381 return isinstance(obj, _list_tuple_types) and len(obj) >= minum
384def isNvector(obj, ellipsoidal=None):
385 '''Is B{C{obj}}ect some C{Nvector}?
387 @arg obj: The object (any C{type}).
388 @kwarg ellipsoidal: If C{None}, return the type of any C{Nvector},
389 if C{True}, only an ellipsoidal C{Nvector type}
390 or if C{False}, only a spherical C{Nvector type}.
392 @return: C{type(B{obj}} if an C{Nvector} of the required type, C{False}
393 if an C{Nvector} of an other type or {None} otherwise.
394 '''
395 if ellipsoidal is not None:
396 try:
397 return obj.ellipsoidalNvector if ellipsoidal else obj.sphericalNvector
398 except AttributeError:
399 return None
400 return isinstanceof(obj, _MODS.nvectorBase.NvectorBase)
403def isodd(x):
404 '''Is B{C{x}} odd?
406 @arg x: Value (C{scalar}).
408 @return: C{True} if odd, C{False} otherwise.
409 '''
410 return bool(int(x) & 1) # == bool(int(x) % 2)
413def isscalar(obj, both=False):
414 '''Is B{C{obj}}ect an C{int} or integer C{float} value?
416 @arg obj: The object (any C{type}).
417 @kwarg both: If C{True}, check L{Fsum<Fsum.residual>}.
419 @return: C{True} if C{int}, C{float} or L{Fsum} with
420 zero residual, C{False} otherwise.
421 '''
422 if isinstance(obj, _Scalars):
423 return not isbool(obj)
424 elif both: # and isinstance(obj, Fsum)
425 try:
426 return bool(obj.residual == 0)
427 except (AttributeError, TypeError):
428 pass # XXX float(int(obj)) == obj?
429 return False
432def issequence(obj, *excls):
433 '''Is B{C{obj}}ect some sequence type?
435 @arg obj: The object (any C{type}).
436 @arg excls: Classes to exclude (C{type}), all positional.
438 @note: Excluding C{tuple} implies excluding C{namedtuple}.
440 @return: C{True} if a sequence, C{False} otherwise.
441 '''
442 return isinstance(obj, _Seqs) and not (excls and isinstance(obj, excls))
445def isstr(obj):
446 '''Is B{C{obj}}ect some string type?
448 @arg obj: The object (any C{type}).
450 @return: C{True} if a C{str}, C{bytes}, ...,
451 C{False} otherwise.
452 '''
453 return isinstance(obj, _Strs)
456def issubclassof(Sub, *Supers):
457 '''Is B{C{Sub}} a class and sub-class of some other class(es)?
459 @arg Sub: The sub-class (C{Class}).
460 @arg Supers: One or more C(super) classes (C{Class}).
462 @return: C{True} if a sub-class of any B{C{Supers}}, C{False}
463 if not (C{bool}) or C{None} if not a class or if no
464 B{C{Supers}} are given or none of those are a class.
465 '''
466 if isclass(Sub):
467 t = tuple(S for S in Supers if isclass(S))
468 if t:
469 return bool(issubclass(Sub, t))
470 return None
473def itemsorted(adict, *items_args, **asorted_reverse):
474 '''Return the items of C{B{adict}} sorted I{alphabetically,
475 case-insensitively} and in I{ascending} order.
477 @arg items_args: Optional positional argument(s) for method
478 C{B{adict}.items(B*{items_args})}.
479 @kwarg asorted_reverse: Use C{B{asorted}=False} for I{alphabetical,
480 case-sensitive} sorting and C{B{reverse}=True} for
481 sorting in C{descending} order.
482 '''
483 def _ins(item): # functools.cmp_to_key
484 k, v = item
485 return k.lower()
487 def _reverse_key(asorted=True, reverse=False):
488 return dict(reverse=reverse, key=_ins if asorted else None)
490 items = adict.items(*items_args) if items_args else adict.items()
491 return sorted(items, **_reverse_key(**asorted_reverse))
494def len2(items):
495 '''Make built-in function L{len} work for generators, iterators,
496 etc. since those can only be started exactly once.
498 @arg items: Generator, iterator, list, range, tuple, etc.
500 @return: 2-Tuple C{(n, items)} of the number of items (C{int})
501 and the items (C{list} or C{tuple}).
502 '''
503 if not isinstance(items, _Seqs): # NOT hasattr(items, '__len__'):
504 items = list(items)
505 return len(items), items
508def map1(fun1, *xs): # XXX map_
509 '''Call a single-argument function to each B{C{xs}}
510 and return a C{tuple} of results.
512 @arg fun1: 1-Arg function (C{callable}).
513 @arg xs: Arguments (C{any positional}).
515 @return: Function results (C{tuple}).
516 '''
517 return tuple(map(fun1, xs))
520def map2(fun, *xs):
521 '''Like Python's B{C{map}} but returning a C{tuple} of results.
523 Unlike Python 2's built-in L{map}, Python 3+ L{map} returns a
524 L{map} object, an iterator-like object which generates the
525 results only once. Converting the L{map} object to a tuple
526 maintains the Python 2 behavior.
528 @arg fun: Function (C{callable}).
529 @arg xs: Arguments (C{all positional}).
531 @return: Function results (C{tuple}).
532 '''
533 return tuple(map(fun, *xs))
536def neg(x, neg0=None):
537 '''Negate C{x} and optionally, negate C{0.0} and C{-0.0}.
539 @kwarg neg0: Defines the return value for zero C{B{x}}: if C{None}
540 return C{0.0}, if C{True} return C{NEG0 if B{x}=0.0}
541 and C{0.0 if B{x}=NEG0} or if C{False} return C{B{x}}
542 I{as-is} (C{bool} or C{None}).
544 @return: C{-B{x} if B{x} else 0.0, NEG0 or B{x}}.
545 '''
546 return (-x) if x else (
547 _0_0 if neg0 is None else (
548 x if not neg0 else (
549 _0_0 if signBit(x) else _MODS.constants.
550 NEG0))) # PYCHOK indent
553def neg_(*xs):
554 '''Negate all C{xs} with L{neg}.
556 @return: A C{map(neg, B{xs})}.
557 '''
558 return map(neg, xs)
561def _neg0(x):
562 '''(INTERNAL) Return C{NEG0 if x < 0 else _0_0},
563 unlike C{_copysign_0_0} which returns C{_N_0_0}.
564 '''
565 return _MODS.constants.NEG0 if x < 0 else _0_0
568def _req_d_by(where, **name):
569 '''(INTERNAL) Get the fully qualified name.
570 '''
571 m = _MODS.named
572 n = m._name__(**name)
573 m = m.modulename(where, prefixed=True)
574 if n:
575 m = _DOT_(m, n)
576 return _SPACE_(_required_, _by_, m)
579def _reverange(n, stop=-1, step=-1):
580 '''(INTERNAL) Reversed range yielding C{n-1, n-1-step, ..., stop+1}.
581 '''
582 return range(n - 1, stop, step)
585def signBit(x):
586 '''Return C{signbit(B{x})}, like C++.
588 @return: C{True} if C{B{x} < 0} or C{NEG0} (C{bool}).
589 '''
590 return x < 0 or _MODS.constants.isneg0(x)
593def _signOf(x, ref): # in .fsums
594 '''(INTERNAL) Return the sign of B{C{x}} versus B{C{ref}}.
595 '''
596 return (-1) if x < ref else (+1 if x > ref else 0)
599def signOf(x):
600 '''Return sign of C{x} as C{int}.
602 @return: -1, 0 or +1 (C{int}).
603 '''
604 try:
605 s = x.signOf() # Fsum instance?
606 except AttributeError:
607 s = _signOf(x, 0)
608 return s
611def splice(iterable, n=2, **fill):
612 '''Split an iterable into C{n} slices.
614 @arg iterable: Items to be spliced (C{list}, C{tuple}, ...).
615 @kwarg n: Number of slices to generate (C{int}).
616 @kwarg fill: Optional fill value for missing items.
618 @return: A generator for each of B{C{n}} slices,
619 M{iterable[i::n] for i=0..n}.
621 @raise TypeError: Invalid B{C{n}}.
623 @note: Each generated slice is a C{tuple} or a C{list},
624 the latter only if the B{C{iterable}} is a C{list}.
626 @example:
628 >>> from pygeodesy import splice
630 >>> a, b = splice(range(10))
631 >>> a, b
632 ((0, 2, 4, 6, 8), (1, 3, 5, 7, 9))
634 >>> a, b, c = splice(range(10), n=3)
635 >>> a, b, c
636 ((0, 3, 6, 9), (1, 4, 7), (2, 5, 8))
638 >>> a, b, c = splice(range(10), n=3, fill=-1)
639 >>> a, b, c
640 ((0, 3, 6, 9), (1, 4, 7, -1), (2, 5, 8, -1))
642 >>> tuple(splice(list(range(9)), n=5))
643 ([0, 5], [1, 6], [2, 7], [3, 8], [4])
645 >>> splice(range(9), n=1)
646 <generator object splice at 0x0...>
647 '''
648 if not isint(n):
649 raise _TypeError(n=n)
651 t = _xiterablen(iterable)
652 if not isinstance(t, _list_tuple_types):
653 t = tuple(t)
655 if n > 1:
656 if fill:
657 fill = _xkwds_get(fill, fill=MISSING)
658 if fill is not MISSING:
659 m = len(t) % n
660 if m > 0: # same type fill
661 t = t + type(t)((fill,) * (n - m))
662 for i in range(n):
663 # XXX t[i::n] chokes PyChecker
664 yield t[slice(i, None, n)]
665 else:
666 yield t # 1 slice, all
669def _splituple(strs, *sep_splits): # in .mgrs, .osgr, .webmercator
670 '''(INTERNAL) Split a C{comma}- or C{whitespace}-separated
671 string into a C{tuple} of stripped strings.
672 '''
673 t = (strs.split(*sep_splits) if sep_splits else
674 strs.replace(_COMMA_, _SPACE_).split()) if strs else ()
675 return tuple(s.strip() for s in t if s)
678def unsigned0(x):
679 '''Unsign if C{0.0}.
681 @return: C{B{x}} if B{C{x}} else C{0.0}.
682 '''
683 return x if x else _0_0
686def _xcopy(obj, deep=False):
687 '''(INTERNAL) Copy an object, shallow or deep.
689 @arg obj: The object to copy (any C{type}).
690 @kwarg deep: If C{True} make a deep, otherwise
691 a shallow copy (C{bool}).
693 @return: The copy of B{C{obj}}.
694 '''
695 return _deepcopy(obj) if deep else _copy(obj)
698def _xdup(obj, deep=False, **items):
699 '''(INTERNAL) Duplicate an object, replacing some attributes.
701 @arg obj: The object to copy (any C{type}).
702 @kwarg deep: If C{True} copy deep, otherwise shallow.
703 @kwarg items: Attributes to be changed (C{any}).
705 @return: A duplicate of B{C{obj}} with modified
706 attributes, if any B{C{items}}.
708 @raise AttributeError: Some B{C{items}} invalid.
709 '''
710 d = _xcopy(obj, deep=deep)
711 for n, v in items.items():
712 if getattr(d, n, v) != v:
713 setattr(d, n, v)
714 elif not hasattr(d, n):
715 t = _MODS.named.classname(obj)
716 t = _SPACE_(_DOT_(t, n), _invalid_)
717 raise _AttributeError(txt=t, obj=obj, **items)
718# if items:
719# _MODS.props._update_all(d)
720 return d
723def _xgeographiclib(where, *required):
724 '''(INTERNAL) Import C{geographiclib} and check required version.
725 '''
726 try:
727 _xpackage(_xgeographiclib)
728 import geographiclib
729 except ImportError as x:
730 raise _xImportError(x, where, Error=LazyImportError)
731 return _xversion(geographiclib, where, *required)
734def _xImportError(exc, where, Error=_ImportError, **name):
735 '''(INTERNAL) Embellish an C{Lazy/ImportError}.
736 '''
737 t = _req_d_by(where, **name)
738 return Error(_Xstr(exc), txt=t, cause=exc)
741def _xinstanceof(*Types, **names_values):
742 '''(INTERNAL) Check C{Types} of all C{name=value} pairs.
744 @arg Types: One or more classes or types (C{class}), all
745 positional.
746 @kwarg names_values: One or more C{B{name}=value} pairs
747 with the C{value} to be checked.
749 @raise TypeError: One B{C{names_values}} pair is not an
750 instance of any of the B{C{Types}}.
751 '''
752 if not (Types and names_values):
753 raise _xAssertionError(_xinstanceof, *Types, **names_values)
755 for n, v in names_values.items():
756 if not isinstance(v, Types):
757 raise _TypesError(n, v, *Types)
760def _xiterable(obj):
761 '''(INTERNAL) Return C{obj} if iterable, otherwise raise C{TypeError}.
762 '''
763 return obj if isiterable(obj) else _xiterror(obj, _xiterable) # PYCHOK None
766def _xiterablen(obj):
767 '''(INTERNAL) Return C{obj} if iterable with C{__len__}, otherwise raise C{TypeError}.
768 '''
769 return obj if isiterablen(obj) else _xiterror(obj, _xiterablen) # PYCHOK None
772def _xiterror(obj, _xwhich):
773 '''(INTERNAL) Helper for C{_xinterable} and C{_xiterablen}.
774 '''
775 t = _not_(_xwhich.__name__[2:]) # _dunder_nameof
776 raise _TypeError(repr(obj), txt=t)
779def _xnumpy(where, *required):
780 '''(INTERNAL) Import C{numpy} and check required version.
781 '''
782 try:
783 _xpackage(_xnumpy)
784 import numpy
785 except ImportError as x:
786 raise _xImportError(x, where)
787 return _xversion(numpy, where, *required)
790def _xor(x, *xs):
791 '''(INTERNAL) Exclusive-or C{x} and C{xs}.
792 '''
793 for x_ in xs:
794 x ^= x_
795 return x
798def _xpackage(_xpkg):
799 '''(INTERNAL) Check dependency to be excluded.
800 '''
801 n = _xpkg.__name__[2:] # _dunder_nameof
802 if n in _XPACKAGES:
803 x = _SPACE_(n, _in_, _PYGEODESY_XPACKAGES_)
804 e = _enquote(_getenv(_PYGEODESY_XPACKAGES_, NN))
805 raise ImportError(_EQUAL_(x, e))
808def _xscalar(**names_values):
809 '''(INTERNAL) Check all C{name=value} pairs to be C{scalar}.
810 '''
811 for n, v in names_values.items():
812 if not isscalar(v):
813 raise _TypeError(n, v, txt=_not_scalar_)
816def _xscipy(where, *required):
817 '''(INTERNAL) Import C{scipy} and check required version.
818 '''
819 try:
820 _xpackage(_xscipy)
821 import scipy
822 except ImportError as x:
823 raise _xImportError(x, where)
824 return _xversion(scipy, where, *required)
827def _xsubclassof(*Classes, **names_values):
828 '''(INTERNAL) Check (super) class of all C{name=value} pairs.
830 @arg Classes: One or more classes or types (C{class}), all
831 positional.
832 @kwarg names_values: One or more C{B{name}=value} pairs
833 with the C{value} to be checked.
835 @raise TypeError: One B{C{names_values}} pair is not a
836 (sub-)class of any of the B{C{Classes}}.
837 '''
838 if not (Classes and names_values):
839 raise _xAssertionError(_xsubclassof, *Classes, **names_values)
841 for n, v in names_values.items():
842 if not issubclassof(v, *Classes):
843 raise _TypesError(n, v, *Classes)
846def _xversion(package, where, *required, **name):
847 '''(INTERNAL) Check the C{package} version vs B{C{required}}.
848 '''
849 if required:
850 t = _version_info(package)
851 if t[:len(required)] < required:
852 t = _SPACE_(package.__name__, # _dunder_nameof
853 _version_, _DOT_(*t),
854 _below_, _DOT_(*required),
855 _req_d_by(where, **name))
856 raise ImportError(t)
857 return package
860def _xzip(*args, **strict): # PYCHOK no cover
861 '''(INTERNAL) Standard C{zip(..., strict=True)}.
862 '''
863 s = _xkwds_get(strict, strict=True)
864 if s:
865 if _zip is zip: # < (3, 10)
866 t = _MODS.streprs.unstr(_xzip, *args, strict=s)
867 raise _NotImplementedError(t, txt=None)
868 return _zip(*args)
869 return zip(*args)
872if _sys_version_info2 < (3, 10): # see .errors
873 _zip = zip # PYCHOK exported
874else: # Python 3.10+
876 def _zip(*args):
877 return zip(*args, strict=True)
879_XPACKAGES = _splituple(_getenv(_PYGEODESY_XPACKAGES_, NN).lower())
881# **) MIT License
882#
883# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
884#
885# Permission is hereby granted, free of charge, to any person obtaining a
886# copy of this software and associated documentation files (the "Software"),
887# to deal in the Software without restriction, including without limitation
888# the rights to use, copy, modify, merge, publish, distribute, sublicense,
889# and/or sell copies of the Software, and to permit persons to whom the
890# Software is furnished to do so, subject to the following conditions:
891#
892# The above copyright notice and this permission notice shall be included
893# in all copies or substantial portions of the Software.
894#
895# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
896# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
897# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
898# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
899# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
900# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
901# OTHER DEALINGS IN THE SOFTWARE.