Coverage for pygeodesy/basics.py: 89%
265 statements
« prev ^ index » next coverage.py v7.2.2, created at 2024-06-27 20:21 -0400
« prev ^ index » next coverage.py v7.2.2, created at 2024-06-27 20:21 -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_get1
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
33# from pygeodesy.unitsBase import _NamedUnit, Str # _MODS
35from copy import copy as _copy, deepcopy as _deepcopy
36from math import copysign as _copysign
37import inspect as _inspect
39__all__ = _ALL_LAZY.basics
40__version__ = '24.06.15'
42_below_ = 'below'
43_list_tuple_types = (list, tuple)
44_PYGEODESY_XPACKAGES_ = 'PYGEODESY_XPACKAGES'
45_required_ = 'required'
47try: # Luciano Ramalho, "Fluent Python", O'Reilly, 2016 p. 395, 2022 p. 577+
48 from numbers import Integral as _Ints, Real as _Scalars # .units
49except ImportError:
50 try:
51 _Ints = int, long # int objects (C{tuple})
52 except NameError: # Python 3+
53 _Ints = int, # int objects (C{tuple})
54 _Scalars = (float,) + _Ints
56try:
57 try: # use C{from collections.abc import ...} in Python 3.9+
58 from collections.abc import Sequence as _Sequence # in .points
59 except ImportError: # no .abc in Python 3.8- and 2.7-
60 from collections import Sequence as _Sequence # in .points
61 if isinstance([], _Sequence) and isinstance((), _Sequence):
62 # and isinstance(range(1), _Sequence):
63 _Seqs = _Sequence
64 else:
65 raise ImportError() # _AssertionError
66except ImportError:
67 _Sequence = tuple # immutable for .points._Basequence
68 _Seqs = list, _Sequence # range for function len2 below
70try:
71 _Bytes = unicode, bytearray # PYCHOK expected
72 _Strs = basestring, str # XXX , bytes
73 str2ub = ub2str = _passarg # avoids UnicodeDecodeError
75 def _Xstr(exc): # PYCHOK no cover
76 '''I{Invoke only with caught ImportError} B{C{exc}}.
78 C{... "can't import name _distributor_init" ...}
80 only for C{numpy}, C{scipy} import errors occurring
81 on arm64 Apple Silicon running macOS' Python 2.7.16?
82 '''
83 t = str(exc)
84 if '_distributor_init' in t:
85 from sys import exc_info
86 from traceback import extract_tb
87 tb = exc_info()[2] # 3-tuple (type, value, traceback)
88 t4 = extract_tb(tb, 1)[0] # 4-tuple (file, line, name, 'import ...')
89 t = _SPACE_("can't", t4[3] or _N_A_)
90 del tb, t4
91 return t
93except NameError: # Python 3+
94 from pygeodesy.interns import _utf_8_
96 _Bytes = bytes, bytearray
97 _Strs = str, # tuple
98 _Xstr = str
100 def str2ub(sb):
101 '''Convert C{str} to C{unicode bytes}.
102 '''
103 if isinstance(sb, _Strs):
104 sb = sb.encode(_utf_8_)
105 return sb
107 def ub2str(ub):
108 '''Convert C{unicode bytes} to C{str}.
109 '''
110 if isinstance(ub, _Bytes):
111 ub = str(ub.decode(_utf_8_))
112 return ub
115def _args_kwds_count2(func, exelf=True):
116 '''(INTERNAL) Get a C{func}'s args and kwds count as 2-tuple
117 C{(nargs, nkwds)}, including arg C{self} for methods.
119 @kwarg exelf: If C{True}, exclude C{self} in the C{args}
120 of a method (C{bool}).
121 '''
122 try:
123 a = k = 0
124 for _, p in _inspect.signature(func).parameters.items():
125 if p.kind is p.POSITIONAL_OR_KEYWORD:
126 if p.default is p.empty:
127 a += 1
128 else:
129 k += 1
130 except AttributeError: # .signature new Python 3+
131 s = _inspect.getargspec(func)
132 k = len(s.defaults or ())
133 a = len(s.args) - k
134 if exelf and a > 0 and _inspect.ismethod(func):
135 a -= 1
136 return a, k
139def _args_kwds_names(func, splast=False):
140 '''(INTERNAL) Get a C{func}'s args and kwds names, including
141 C{self} for methods.
143 @kwarg splast: If C{True}, split the last keyword argument
144 at UNDERscores (C{bool}).
146 @note: Python 2 may I{not} include the C{*args} nor the
147 C{**kwds} names.
148 '''
149 try:
150 args_kwds = _inspect.signature(func).parameters.keys()
151 except AttributeError: # .signature new Python 3+
152 args_kwds = _inspect.getargspec(func).args
153 if splast and args_kwds:
154 args_kwds = list(args_kwds)
155 t = args_kwds[-1:]
156 if t:
157 s = t[0].strip(_UNDER_).split(_UNDER_)
158 if len(s) > 1 or s != t:
159 args_kwds += s
160 return tuple(args_kwds)
163def clips(sb, limit=50, white=NN):
164 '''Clip a string to the given length limit.
166 @arg sb: String (C{str} or C{bytes}).
167 @kwarg limit: Length limit (C{int}).
168 @kwarg white: Optionally, replace all whitespace (C{str}).
170 @return: The clipped or unclipped B{C{sb}}.
171 '''
172 T = type(sb)
173 if len(sb) > limit > 8:
174 h = limit // 2
175 sb = T(_ELLIPSIS4_).join((sb[:h], sb[-h:]))
176 if white: # replace whitespace
177 sb = T(white).join(sb.split())
178 return sb
181def copysign0(x, y):
182 '''Like C{math.copysign(x, y)} except C{zero}, I{unsigned}.
184 @return: C{math.copysign(B{x}, B{y})} if B{C{x}} else
185 C{type(B{x})(0)}.
186 '''
187 return _copysign(x, (y if y else 0)) if x else copytype(0, x)
190def copytype(x, y):
191 '''Return the value of B{x} as C{type} of C{y}.
193 @return: C{type(B{y})(B{x})}.
194 '''
195 return type(y)(x if x else _0_0)
198def _enumereverse(iterable):
199 '''(INTERNAL) Reversed C{enumberate}.
200 '''
201 for j in _reverange(len(iterable)):
202 yield j, iterable[j]
205def halfs2(str2):
206 '''Split a string in 2 halfs.
208 @arg str2: String to split (C{str}).
210 @return: 2-Tuple C{(_1st, _2nd)} half (C{str}).
212 @raise ValueError: Zero or odd C{len(B{str2})}.
213 '''
214 h, r = divmod(len(str2), 2)
215 if r or not h:
216 raise _ValueError(str2=str2, txt=_odd_)
217 return str2[:h], str2[h:]
220def int1s(x):
221 '''Count the number of 1-bits in an C{int}, I{unsigned}.
223 @note: C{int1s(-B{x}) == int1s(abs(B{x}))}.
224 '''
225 try:
226 return x.bit_count() # Python 3.10+
227 except AttributeError:
228 # bin(-x) = '-' + bin(abs(x))
229 return bin(x).count(_1_)
232def isbool(obj):
233 '''Is B{C{obj}}ect a C{bool}ean?
235 @arg obj: The object (any C{type}).
237 @return: C{True} if C{bool}ean, C{False} otherwise.
238 '''
239 return isinstance(obj, bool) # and (obj is False
240# or obj is True)
242assert not (isbool(1) or isbool(0) or isbool(None)) # PYCHOK 2
245def isCartesian(obj, ellipsoidal=None):
246 '''Is B{C{obj}}ect some C{Cartesian}?
248 @arg obj: The object (any C{type}).
249 @kwarg ellipsoidal: If C{None}, return the type of any C{Cartesian},
250 if C{True}, only an ellipsoidal C{Cartesian type}
251 or if C{False}, only a spherical C{Cartesian type}.
253 @return: C{type(B{obj}} if a C{Cartesian} of the required type, C{False}
254 if a C{Cartesian} of an other type or {None} otherwise.
255 '''
256 if ellipsoidal is not None:
257 try:
258 return obj.ellipsoidalCartesian if ellipsoidal else obj.sphericalCartesian
259 except AttributeError:
260 return None
261 return isinstanceof(obj, _MODS.cartesianBase.CartesianBase)
264if _FOR_DOCS: # XXX avoid epydoc Python 2.7 error
266 def isclass(obj):
267 '''Is B{C{obj}}ect a C{Class} or C{type}?
268 '''
269 return _inspect.isclass(obj)
270else:
271 isclass = _inspect.isclass
274def iscomplex(obj, both=False):
275 '''Is B{C{obj}}ect a C{complex} or complex literal C{str}?
277 @arg obj: The object (any C{type}).
278 @kwarg both: If C{True}, check complex C{str} (C{bool}).
280 @return: C{True} if C{complex}, C{False} otherwise.
281 '''
282 try: # hasattr('conjugate', 'real' and 'imag')
283 return isinstance(obj, complex) or bool(both and isstr(obj) and
284 isinstance(complex(obj), complex)) # numbers.Complex?
285 except (TypeError, ValueError):
286 return False
289def isDEPRECATED(obj):
290 '''Is B{C{obj}}ect a C{DEPRECATED} class, method or function?
292 @return: C{True} if C{DEPRECATED}, {False} if not or
293 C{None} if undetermined.
294 '''
295 try: # XXX inspect.getdoc(obj) or obj.__doc__
296 doc = obj.__doc__.lstrip()
297 return bool(doc and doc.startswith(_DEPRECATED_))
298 except AttributeError:
299 return None
302def isfloat(obj, both=False):
303 '''Is B{C{obj}}ect a C{float} or float literal C{str}?
305 @arg obj: The object (any C{type}).
306 @kwarg both: If C{True}, check float C{str} (C{bool}).
308 @return: C{True} if C{float}, C{False} otherwise.
309 '''
310 try:
311 return isinstance(obj, float) or bool(both and
312 isstr(obj) and isinstance(float(obj), float))
313 except (TypeError, ValueError):
314 return False
317try:
318 isidentifier = str.isidentifier # Python 3, must be str
319except AttributeError: # Python 2-
321 def isidentifier(obj):
322 '''Is B{C{obj}}ect a Python identifier?
323 '''
324 return bool(obj and isstr(obj)
325 and obj.replace(_UNDER_, NN).isalnum()
326 and not obj[:1].isdigit())
329def isinstanceof(obj, *Classes):
330 '''Is B{C{obj}}ect an instance of one of the C{Classes}?
332 @arg obj: The object (any C{type}).
333 @arg Classes: One or more classes (C{Class}).
335 @return: C{type(B{obj}} if one of the B{C{Classes}},
336 C{None} otherwise.
337 '''
338 return type(obj) if isinstance(obj, Classes) else None
341def isint(obj, both=False):
342 '''Is B{C{obj}}ect an C{int} or integer C{float} value?
344 @arg obj: The object (any C{type}).
345 @kwarg both: If C{True}, check C{float} and L{Fsum}
346 type and value (C{bool}).
348 @return: C{True} if C{int} or I{integer} C{float}
349 or L{Fsum}, C{False} otherwise.
351 @note: Both C{isint(True)} and C{isint(False)} return
352 C{False} (and no longer C{True}).
353 '''
354 if isinstance(obj, _Ints):
355 return not isbool(obj)
356 elif both: # and isinstance(obj, (float, Fsum))
357 try: # NOT , _Scalars) to include Fsum!
358 return obj.is_integer()
359 except AttributeError:
360 pass # XXX float(int(obj)) == obj?
361 return False
364def isiterable(obj):
365 '''Is B{C{obj}}ect C{iterable}?
367 @arg obj: The object (any C{type}).
369 @return: C{True} if C{iterable}, C{False} otherwise.
370 '''
371 # <https://PyPI.org/project/isiterable/>
372 return hasattr(obj, '__iter__') # map, range, set
375def isiterablen(obj):
376 '''Is B{C{obj}}ect C{iterable} and has C{len}gth?
378 @arg obj: The object (any C{type}).
380 @return: C{True} if C{iterable} with C{len}gth, C{False} otherwise.
381 '''
382 return hasattr(obj, '__len__') and hasattr(obj, '__getitem__')
385try:
386 from keyword import iskeyword # Python 2.7+
387except ImportError:
389 def iskeyword(unused):
390 '''Not Implemented, C{False} always.
391 '''
392 return False
395def isLatLon(obj, ellipsoidal=None):
396 '''Is B{C{obj}}ect some C{LatLon}?
398 @arg obj: The object (any C{type}).
399 @kwarg ellipsoidal: If C{None}, return the type of any C{LatLon},
400 if C{True}, only an ellipsoidal C{LatLon type}
401 or if C{False}, only a spherical C{LatLon type}.
403 @return: C{type(B{obj}} if a C{LatLon} of the required type, C{False}
404 if a C{LatLon} of an other type or {None} otherwise.
405 '''
406 if ellipsoidal is not None:
407 try:
408 return obj.ellipsoidalLatLon if ellipsoidal else obj.sphericalLatLon
409 except AttributeError:
410 return None
411 return isinstanceof(obj, _MODS.latlonBase.LatLonBase)
414def islistuple(obj, minum=0):
415 '''Is B{C{obj}}ect a C{list} or C{tuple} with non-zero length?
417 @arg obj: The object (any C{type}).
418 @kwarg minum: Minimal C{len} required C({int}).
420 @return: C{True} if a C{list} or C{tuple} with C{len} at
421 least B{C{minum}}, C{False} otherwise.
422 '''
423 return isinstance(obj, _list_tuple_types) and len(obj) >= minum
426def isNvector(obj, ellipsoidal=None):
427 '''Is B{C{obj}}ect some C{Nvector}?
429 @arg obj: The object (any C{type}).
430 @kwarg ellipsoidal: If C{None}, return the type of any C{Nvector},
431 if C{True}, only an ellipsoidal C{Nvector type}
432 or if C{False}, only a spherical C{Nvector type}.
434 @return: C{type(B{obj}} if an C{Nvector} of the required type, C{False}
435 if an C{Nvector} of an other type or {None} otherwise.
436 '''
437 if ellipsoidal is not None:
438 try:
439 return obj.ellipsoidalNvector if ellipsoidal else obj.sphericalNvector
440 except AttributeError:
441 return None
442 return isinstanceof(obj, _MODS.nvectorBase.NvectorBase)
445def isodd(x):
446 '''Is B{C{x}} odd?
448 @arg x: Value (C{scalar}).
450 @return: C{True} if odd, C{False} otherwise.
451 '''
452 return bool(int(x) & 1) # == bool(int(x) % 2)
455def isscalar(obj, both=False):
456 '''Is B{C{obj}}ect an C{int} or integer C{float} value?
458 @arg obj: The object (any C{type}).
459 @kwarg both: If C{True}, check L{Fsum<Fsum.residual>}.
461 @return: C{True} if C{int}, C{float} or L{Fsum} with
462 zero residual, C{False} otherwise.
463 '''
464 if isinstance(obj, _Scalars):
465 return not isbool(obj)
466 elif both: # and isinstance(obj, Fsum)
467 try:
468 return bool(obj.residual == 0)
469 except (AttributeError, TypeError):
470 pass # XXX float(int(obj)) == obj?
471 return False
474def issequence(obj, *excls):
475 '''Is B{C{obj}}ect some sequence type?
477 @arg obj: The object (any C{type}).
478 @arg excls: Classes to exclude (C{type}), all positional.
480 @note: Excluding C{tuple} implies excluding C{namedtuple}.
482 @return: C{True} if a sequence, C{False} otherwise.
483 '''
484 return isinstance(obj, _Seqs) and not (excls and isinstance(obj, excls))
487def isstr(obj):
488 '''Is B{C{obj}}ect some string type?
490 @arg obj: The object (any C{type}).
492 @return: C{True} if a C{str}, C{bytes}, ...,
493 C{False} otherwise.
494 '''
495 return isinstance(obj, _Strs)
498def issubclassof(Sub, *Supers):
499 '''Is B{C{Sub}} a class and sub-class of some other class(es)?
501 @arg Sub: The sub-class (C{Class}).
502 @arg Supers: One or more C(super) classes (C{Class}).
504 @return: C{True} if a sub-class of any B{C{Supers}}, C{False}
505 if not (C{bool}) or C{None} if not a class or if no
506 B{C{Supers}} are given or none of those are a class.
507 '''
508 if isclass(Sub):
509 t = tuple(S for S in Supers if isclass(S))
510 if t:
511 return bool(issubclass(Sub, t))
512 return None
515def itemsorted(adict, *items_args, **asorted_reverse):
516 '''Return the items of C{B{adict}} sorted I{alphabetically,
517 case-insensitively} and in I{ascending} order.
519 @arg items_args: Optional positional argument(s) for method
520 C{B{adict}.items(B*{items_args})}.
521 @kwarg asorted_reverse: Use C{B{asorted}=False} for I{alphabetical,
522 case-sensitive} sorting and C{B{reverse}=True} for
523 sorting in C{descending} order.
524 '''
525 def _ins(item): # functools.cmp_to_key
526 k, v = item
527 return k.lower()
529 def _reverse_key(asorted=True, reverse=False):
530 return dict(reverse=reverse, key=_ins if asorted else None)
532 items = adict.items(*items_args) if items_args else adict.items()
533 return sorted(items, **_reverse_key(**asorted_reverse))
536def len2(items):
537 '''Make built-in function L{len} work for generators, iterators,
538 etc. since those can only be started exactly once.
540 @arg items: Generator, iterator, list, range, tuple, etc.
542 @return: 2-Tuple C{(n, items)} of the number of items (C{int})
543 and the items (C{list} or C{tuple}).
544 '''
545 if not isinstance(items, _Seqs): # NOT hasattr(items, '__len__'):
546 items = list(items)
547 return len(items), items
550def map1(fun1, *xs): # XXX map_
551 '''Call a single-argument function to each B{C{xs}}
552 and return a C{tuple} of results.
554 @arg fun1: 1-Arg function (C{callable}).
555 @arg xs: Arguments (C{any positional}).
557 @return: Function results (C{tuple}).
558 '''
559 return tuple(map(fun1, xs))
562def map2(fun, *xs):
563 '''Like Python's B{C{map}} but returning a C{tuple} of results.
565 Unlike Python 2's built-in L{map}, Python 3+ L{map} returns a
566 L{map} object, an iterator-like object which generates the
567 results only once. Converting the L{map} object to a tuple
568 maintains the Python 2 behavior.
570 @arg fun: Function (C{callable}).
571 @arg xs: Arguments (C{all positional}).
573 @return: Function results (C{tuple}).
574 '''
575 return tuple(map(fun, *xs))
578def neg(x, neg0=None):
579 '''Negate C{x} and optionally, negate C{0.0} and C{-0.0}.
581 @kwarg neg0: Defines the return value for zero C{B{x}}: if C{None}
582 return C{0.0}, if C{True} return C{NEG0 if B{x}=0.0}
583 and C{0.0 if B{x}=NEG0} or if C{False} return C{B{x}}
584 I{as-is} (C{bool} or C{None}).
586 @return: C{-B{x} if B{x} else 0.0, NEG0 or B{x}}.
587 '''
588 return (-x) if x else (
589 _0_0 if neg0 is None else (
590 x if not neg0 else (
591 _0_0 if signBit(x) else _MODS.constants.
592 NEG0))) # PYCHOK indent
595def neg_(*xs):
596 '''Negate all C{xs} with L{neg}.
598 @return: A C{map(neg, B{xs})}.
599 '''
600 return map(neg, xs)
603def _neg0(x):
604 '''(INTERNAL) Return C{NEG0 if x < 0 else _0_0},
605 unlike C{_copysign_0_0} which returns C{_N_0_0}.
606 '''
607 return _MODS.constants.NEG0 if x < 0 else _0_0
610def _req_d_by(where, **name):
611 '''(INTERNAL) Get the fully qualified name.
612 '''
613 m = _MODS.named
614 n = m._name__(**name)
615 m = m.modulename(where, prefixed=True)
616 if n:
617 m = _DOT_(m, n)
618 return _SPACE_(_required_, _by_, m)
621def _reverange(n, stop=-1, step=-1):
622 '''(INTERNAL) Reversed range yielding C{n-1, n-1-step, ..., stop+1}.
623 '''
624 return range(n - 1, stop, step)
627def signBit(x):
628 '''Return C{signbit(B{x})}, like C++.
630 @return: C{True} if C{B{x} < 0} or C{NEG0} (C{bool}).
631 '''
632 return x < 0 or _MODS.constants.isneg0(x)
635def _signOf(x, ref): # in .fsums
636 '''(INTERNAL) Return the sign of B{C{x}} versus B{C{ref}}.
637 '''
638 return (-1) if x < ref else (+1 if x > ref else 0)
641def signOf(x):
642 '''Return sign of C{x} as C{int}.
644 @return: -1, 0 or +1 (C{int}).
645 '''
646 try:
647 s = x.signOf() # Fsum instance?
648 except AttributeError:
649 s = _signOf(x, 0)
650 return s
653def splice(iterable, n=2, **fill):
654 '''Split an iterable into C{n} slices.
656 @arg iterable: Items to be spliced (C{list}, C{tuple}, ...).
657 @kwarg n: Number of slices to generate (C{int}).
658 @kwarg fill: Optional fill value for missing items.
660 @return: A generator for each of B{C{n}} slices,
661 M{iterable[i::n] for i=0..n}.
663 @raise TypeError: Invalid B{C{n}}.
665 @note: Each generated slice is a C{tuple} or a C{list},
666 the latter only if the B{C{iterable}} is a C{list}.
668 @example:
670 >>> from pygeodesy import splice
672 >>> a, b = splice(range(10))
673 >>> a, b
674 ((0, 2, 4, 6, 8), (1, 3, 5, 7, 9))
676 >>> a, b, c = splice(range(10), n=3)
677 >>> a, b, c
678 ((0, 3, 6, 9), (1, 4, 7), (2, 5, 8))
680 >>> a, b, c = splice(range(10), n=3, fill=-1)
681 >>> a, b, c
682 ((0, 3, 6, 9), (1, 4, 7, -1), (2, 5, 8, -1))
684 >>> tuple(splice(list(range(9)), n=5))
685 ([0, 5], [1, 6], [2, 7], [3, 8], [4])
687 >>> splice(range(9), n=1)
688 <generator object splice at 0x0...>
689 '''
690 if not isint(n):
691 raise _TypeError(n=n)
693 t = _xiterablen(iterable)
694 if not isinstance(t, _list_tuple_types):
695 t = tuple(t)
697 if n > 1:
698 if fill:
699 fill = _xkwds_get1(fill, fill=MISSING)
700 if fill is not MISSING:
701 m = len(t) % n
702 if m > 0: # same type fill
703 t = t + type(t)((fill,) * (n - m))
704 for i in range(n):
705 # XXX t[i::n] chokes PyChecker
706 yield t[slice(i, None, n)]
707 else:
708 yield t # 1 slice, all
711def _splituple(strs, *sep_splits): # in .mgrs, .osgr, .webmercator
712 '''(INTERNAL) Split a C{comma}- or C{whitespace}-separated
713 string into a C{tuple} of stripped strings.
714 '''
715 t = (strs.split(*sep_splits) if sep_splits else
716 strs.replace(_COMMA_, _SPACE_).split()) if strs else ()
717 return tuple(s.strip() for s in t if s)
720def unsigned0(x):
721 '''Unsign if C{0.0}.
723 @return: C{B{x}} if B{C{x}} else C{0.0}.
724 '''
725 return x if x else _0_0
728def _xcopy(obj, deep=False):
729 '''(INTERNAL) Copy an object, shallow or deep.
731 @arg obj: The object to copy (any C{type}).
732 @kwarg deep: If C{True} make a deep, otherwise
733 a shallow copy (C{bool}).
735 @return: The copy of B{C{obj}}.
736 '''
737 return _deepcopy(obj) if deep else _copy(obj)
740def _xdup(obj, deep=False, **items):
741 '''(INTERNAL) Duplicate an object, replacing some attributes.
743 @arg obj: The object to copy (any C{type}).
744 @kwarg deep: If C{True} copy deep, otherwise shallow.
745 @kwarg items: Attributes to be changed (C{any}).
747 @return: A duplicate of B{C{obj}} with modified
748 attributes, if any B{C{items}}.
750 @raise AttributeError: Some B{C{items}} invalid.
751 '''
752 d = _xcopy(obj, deep=deep)
753 for n, v in items.items():
754 if getattr(d, n, v) != v:
755 setattr(d, n, v)
756 elif not hasattr(d, n):
757 t = _MODS.named.classname(obj)
758 t = _SPACE_(_DOT_(t, n), _invalid_)
759 raise _AttributeError(txt=t, obj=obj, **items)
760# if items:
761# _MODS.props._update_all(d)
762 return d
765def _xgeographiclib(where, *required):
766 '''(INTERNAL) Import C{geographiclib} and check required version.
767 '''
768 try:
769 _xpackage(_xgeographiclib)
770 import geographiclib
771 except ImportError as x:
772 raise _xImportError(x, where, Error=LazyImportError)
773 return _xversion(geographiclib, where, *required)
776def _xImportError(exc, where, Error=_ImportError, **name):
777 '''(INTERNAL) Embellish an C{Lazy/ImportError}.
778 '''
779 t = _req_d_by(where, **name)
780 return Error(_Xstr(exc), txt=t, cause=exc)
783def _xinstanceof(*Types, **names_values):
784 '''(INTERNAL) Check C{Types} of all C{name=value} pairs.
786 @arg Types: One or more classes or types (C{class}), all
787 positional.
788 @kwarg names_values: One or more C{B{name}=value} pairs
789 with the C{value} to be checked.
791 @raise TypeError: One B{C{names_values}} pair is not an
792 instance of any of the B{C{Types}}.
793 '''
794 if not (Types and names_values):
795 raise _xAssertionError(_xinstanceof, *Types, **names_values)
797 for n, v in names_values.items():
798 if not isinstance(v, Types):
799 raise _TypesError(n, v, *Types)
802def _xiterable(obj):
803 '''(INTERNAL) Return C{obj} if iterable, otherwise raise C{TypeError}.
804 '''
805 return obj if isiterable(obj) else _xiterror(obj, _xiterable) # PYCHOK None
808def _xiterablen(obj):
809 '''(INTERNAL) Return C{obj} if iterable with C{__len__}, otherwise raise C{TypeError}.
810 '''
811 return obj if isiterablen(obj) else _xiterror(obj, _xiterablen) # PYCHOK None
814def _xiterror(obj, _xwhich):
815 '''(INTERNAL) Helper for C{_xinterable} and C{_xiterablen}.
816 '''
817 t = _not_(_xwhich.__name__[2:]) # _dunder_nameof
818 raise _TypeError(repr(obj), txt=t)
821def _xnumpy(where, *required):
822 '''(INTERNAL) Import C{numpy} and check required version.
823 '''
824 try:
825 _xpackage(_xnumpy)
826 import numpy
827 except ImportError as x:
828 raise _xImportError(x, where)
829 return _xversion(numpy, where, *required)
832def _xor(x, *xs):
833 '''(INTERNAL) Exclusive-or C{x} and C{xs}.
834 '''
835 for x_ in xs:
836 x ^= x_
837 return x
840def _xpackage(_xpkg):
841 '''(INTERNAL) Check dependency to be excluded.
842 '''
843 n = _xpkg.__name__[2:] # _dunder_nameof
844 if n in _XPACKAGES:
845 x = _SPACE_(n, _in_, _PYGEODESY_XPACKAGES_)
846 e = _enquote(_getenv(_PYGEODESY_XPACKAGES_, NN))
847 raise ImportError(_EQUAL_(x, e))
850def _xscalar(**names_values):
851 '''(INTERNAL) Check all C{name=value} pairs to be C{scalar}.
852 '''
853 for n, v in names_values.items():
854 if not isscalar(v):
855 raise _TypeError(n, v, txt=_not_scalar_)
858def _xscipy(where, *required):
859 '''(INTERNAL) Import C{scipy} and check required version.
860 '''
861 try:
862 _xpackage(_xscipy)
863 import scipy
864 except ImportError as x:
865 raise _xImportError(x, where)
866 return _xversion(scipy, where, *required)
869def _xsubclassof(*Classes, **names_values):
870 '''(INTERNAL) Check (super) class of all C{name=value} pairs.
872 @arg Classes: One or more classes or types (C{class}), all
873 positional.
874 @kwarg names_values: One or more C{B{name}=value} pairs
875 with the C{value} to be checked.
877 @raise TypeError: One B{C{names_values}} pair is not a
878 (sub-)class of any of the B{C{Classes}}.
879 '''
880 if not (Classes and names_values):
881 raise _xAssertionError(_xsubclassof, *Classes, **names_values)
883 for n, v in names_values.items():
884 if not issubclassof(v, *Classes):
885 raise _TypesError(n, v, *Classes)
888def _xversion(package, where, *required, **name):
889 '''(INTERNAL) Check the C{package} version vs B{C{required}}.
890 '''
891 if required:
892 t = _version_info(package)
893 if t[:len(required)] < required:
894 t = _SPACE_(package.__name__, # _dunder_nameof
895 _version_, _DOT_(*t),
896 _below_, _DOT_(*required),
897 _req_d_by(where, **name))
898 raise ImportError(t)
899 return package
902def _xzip(*args, **strict): # PYCHOK no cover
903 '''(INTERNAL) Standard C{zip(..., strict=True)}.
904 '''
905 s = _xkwds_get1(strict, strict=True)
906 if s:
907 if _zip is zip: # < (3, 10)
908 t = _MODS.streprs.unstr(_xzip, *args, strict=s)
909 raise _NotImplementedError(t, txt=None)
910 return _zip(*args)
911 return zip(*args)
914if _sys_version_info2 < (3, 10): # see .errors
915 _zip = zip # PYCHOK exported
916else: # Python 3.10+
918 def _zip(*args):
919 return zip(*args, strict=True)
921_XPACKAGES = _splituple(_getenv(_PYGEODESY_XPACKAGES_, NN).lower())
923# **) MIT License
924#
925# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
926#
927# Permission is hereby granted, free of charge, to any person obtaining a
928# copy of this software and associated documentation files (the "Software"),
929# to deal in the Software without restriction, including without limitation
930# the rights to use, copy, modify, merge, publish, distribute, sublicense,
931# and/or sell copies of the Software, and to permit persons to whom the
932# Software is furnished to do so, subject to the following conditions:
933#
934# The above copyright notice and this permission notice shall be included
935# in all copies or substantial portions of the Software.
936#
937# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
938# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
939# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
940# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
941# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
942# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
943# OTHER DEALINGS IN THE SOFTWARE.