Coverage for pygeodesy/basics.py: 95%
241 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-12 16:17 -0500
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-12 16:17 -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
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
22# from pygeodesy.fsums import _isFsum_2Tuple # _MODS
23from pygeodesy.internals import _0_0, _enquote, _getenv, _passarg, _PYGEODESY, \
24 _version_info
25from pygeodesy.interns import MISSING, NN, _1_, _by_, _COMMA_, _DOT_, _DEPRECATED_, \
26 _ELLIPSIS4_, _EQUAL_, _in_, _invalid_, _N_A_, _not_, \
27 _not_scalar_, _odd_, _SPACE_, _UNDER_, _version_
28# from pygeodesy.latlonBase import LatLonBase # _MODS
29from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, LazyImportError
30# from pygeodesy.named import classname, modulename, _name__ # _MODS
31# from pygeodesy.nvectorBase import NvectorBase # _MODS
32# from pygeodesy.props import _update_all # _MODS
33# from pygeodesy.streprs import Fmt # _MODS
35from copy import copy as _copy, deepcopy as _deepcopy
36from math import copysign as _copysign
37# import inspect as _inspect # _MODS
39__all__ = _ALL_LAZY.basics
40__version__ = '24.11.02'
42_below_ = 'below'
43_list_tuple_types = (list, tuple)
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 in .internals
71 _Strs = basestring, str # XXX str == 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 # in .internals
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
114# def _args_kwds_count2(func, exelf=True): # in .formy
115# '''(INTERNAL) Get a C{func}'s args and kwds count as 2-tuple
116# C{(nargs, nkwds)}, including arg C{self} for methods.
117#
118# @kwarg exelf: If C{True}, exclude C{self} in the C{args}
119# of a method (C{bool}).
120# '''
121# i = _MODS.inspect
122# try:
123# a = k = 0
124# for _, p in i.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: # Python 2-
131# s = i.getargspec(func)
132# k = len(s.defaults or ())
133# a = len(s.args) - k
134# if exelf and a > 0 and i.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 i = _MODS.inspect
150 try:
151 args_kwds = i.signature(func).parameters.keys()
152 except AttributeError: # Python 2-
153 args_kwds = i.getargspec(func).args
154 if splast and args_kwds: # PYCHOK no cover
155 args_kwds = list(args_kwds)
156 t = args_kwds[-1:]
157 if t:
158 s = t[0].strip(_UNDER_).split(_UNDER_)
159 if len(s) > 1 or s != t:
160 args_kwds += s
161 return tuple(args_kwds)
164def clips(sb, limit=50, white=NN, length=False):
165 '''Clip a string to the given length limit.
167 @arg sb: String (C{str} or C{bytes}).
168 @kwarg limit: Length limit (C{int}).
169 @kwarg white: Optionally, replace all whitespace (C{str}).
170 @kwarg length: If C{True}, append the original I{[length]} (C{bool}).
172 @return: The clipped or unclipped B{C{sb}}.
173 '''
174 T, n = type(sb), len(sb)
175 if n > limit > 8:
176 h = limit // 2
177 sb = T(_ELLIPSIS4_).join((sb[:h], sb[-h:]))
178 if length:
179 n = _MODS.streprs.Fmt.SQUARE(n)
180 sb = T(NN).join((sb, n))
181 if white: # replace whitespace
182 sb = T(white).join(sb.split())
183 return sb
186def copysign0(x, y):
187 '''Like C{math.copysign(x, y)} except C{zero}, I{unsigned}.
189 @return: C{math.copysign(B{x}, B{y})} if B{C{x}} else
190 C{type(B{x})(0)}.
191 '''
192 return _copysign(x, (y if y else 0)) if x else copytype(0, x)
195def copytype(x, y):
196 '''Return the value of B{x} as C{type} of C{y}.
198 @return: C{type(B{y})(B{x})}.
199 '''
200 return type(y)(x if x else _0_0)
203def _enumereverse(iterable):
204 '''(INTERNAL) Reversed C{enumberate}.
205 '''
206 for j in _reverange(len(iterable)):
207 yield j, iterable[j]
210def halfs2(str2):
211 '''Split a string in 2 halfs.
213 @arg str2: String to split (C{str}).
215 @return: 2-Tuple C{(_1st, _2nd)} half (C{str}).
217 @raise ValueError: Zero or odd C{len(B{str2})}.
218 '''
219 h, r = divmod(len(str2), 2)
220 if r or not h:
221 raise _ValueError(str2=str2, txt=_odd_)
222 return str2[:h], str2[h:]
225def int1s(x): # PYCHOK no cover
226 '''Count the number of 1-bits in an C{int}, I{unsigned}.
228 @note: C{int1s(-B{x}) == int1s(abs(B{x}))}.
229 '''
230 try:
231 return x.bit_count() # Python 3.10+
232 except AttributeError:
233 # bin(-x) = '-' + bin(abs(x))
234 return bin(x).count(_1_)
237def isbool(obj):
238 '''Is B{C{obj}}ect a C{bool}ean?
240 @arg obj: The object (any C{type}).
242 @return: C{True} if C{bool}ean, C{False} otherwise.
243 '''
244 return isinstance(obj, bool) # and (obj is False
245# or obj is True)
247assert not (isbool(1) or isbool(0) or isbool(None)) # PYCHOK 2
250def isCartesian(obj, ellipsoidal=None):
251 '''Is B{C{obj}}ect some C{Cartesian}?
253 @arg obj: The object (any C{type}).
254 @kwarg ellipsoidal: If C{None}, return the type of any C{Cartesian},
255 if C{True}, only an ellipsoidal C{Cartesian type}
256 or if C{False}, only a spherical C{Cartesian type}.
258 @return: C{type(B{obj}} if a C{Cartesian} of the required type, C{False}
259 if a C{Cartesian} of an other type or {None} otherwise.
260 '''
261 if ellipsoidal is not None:
262 try:
263 return obj.ellipsoidalCartesian if ellipsoidal else obj.sphericalCartesian
264 except AttributeError:
265 return None
266 return isinstanceof(obj, _MODS.cartesianBase.CartesianBase)
269def isclass(obj): # XXX avoid epydoc Python 2.7 error
270 '''Is B{C{obj}}ect a C{Class} or C{type}?
271 '''
272 return _MODS.inspect.isclass(obj)
275def iscomplex(obj, both=False):
276 '''Is B{C{obj}}ect a C{complex} or complex literal C{str}?
278 @arg obj: The object (any C{type}).
279 @kwarg both: If C{True}, check complex C{str} (C{bool}).
281 @return: C{True} if C{complex}, C{False} otherwise.
282 '''
283 try: # hasattr('conjugate', 'real' and 'imag')
284 return isinstance(obj, complex) or bool(both and isstr(obj) and
285 isinstance(complex(obj), complex)) # numbers.Complex?
286 except (TypeError, ValueError):
287 return False
290def isDEPRECATED(obj):
291 '''Is B{C{obj}}ect a C{DEPRECATED} class, method or function?
293 @return: C{True} if C{DEPRECATED}, {False} if not or
294 C{None} if undetermined.
295 '''
296 try: # XXX inspect.getdoc(obj) or obj.__doc__
297 doc = obj.__doc__.lstrip()
298 return bool(doc and doc.startswith(_DEPRECATED_))
299 except AttributeError:
300 return None
303def isfloat(obj, both=False):
304 '''Is B{C{obj}}ect a C{float} or float literal C{str}?
306 @arg obj: The object (any C{type}).
307 @kwarg both: If C{True}, check float C{str} (C{bool}).
309 @return: C{True} if C{float}, C{False} otherwise.
310 '''
311 try:
312 return isinstance(obj, float) or bool(both and
313 isstr(obj) and isinstance(float(obj), float))
314 except (TypeError, ValueError):
315 return False
318try:
319 isidentifier = str.isidentifier # Python 3, must be str
320except AttributeError: # Python 2-
322 def isidentifier(obj):
323 '''Is B{C{obj}}ect a Python identifier?
324 '''
325 return bool(obj and isstr(obj)
326 and obj.replace(_UNDER_, NN).isalnum()
327 and not obj[:1].isdigit())
330def isinstanceof(obj, *Classes):
331 '''Is B{C{obj}}ect an instance of one of the C{Classes}?
333 @arg obj: The object (any C{type}).
334 @arg Classes: One or more classes (C{Class}).
336 @return: C{type(B{obj}} if one of the B{C{Classes}},
337 C{None} otherwise.
338 '''
339 return type(obj) if isinstance(obj, Classes) else None
342def isint(obj, both=False):
343 '''Is B{C{obj}}ect an C{int} or integer C{float} value?
345 @arg obj: The object (any C{type}).
346 @kwarg both: If C{True}, check C{float} and L{Fsum}
347 type and value (C{bool}).
349 @return: C{True} if C{int} or I{integer} C{float}
350 or L{Fsum}, C{False} otherwise.
352 @note: Both C{isint(True)} and C{isint(False)} return
353 C{False} (and no longer C{True}).
354 '''
355 if isinstance(obj, _Ints):
356 return not isbool(obj)
357 elif both: # and isinstance(obj, (float, Fsum))
358 try: # NOT , _Scalars) to include Fsum!
359 return obj.is_integer()
360 except AttributeError:
361 pass # XXX float(int(obj)) == obj?
362 return False
365def isiterable(obj):
366 '''Is B{C{obj}}ect C{iterable}?
368 @arg obj: The object (any C{type}).
370 @return: C{True} if C{iterable}, C{False} otherwise.
371 '''
372 # <https://PyPI.org/project/isiterable/>
373 return hasattr(obj, '__iter__') # map, range, set
376def isiterablen(obj):
377 '''Is B{C{obj}}ect C{iterable} and has C{len}gth?
379 @arg obj: The object (any C{type}).
381 @return: C{True} if C{iterable} with C{len}gth, C{False} otherwise.
382 '''
383 return hasattr(obj, '__len__') and hasattr(obj, '__getitem__')
386try:
387 from keyword import iskeyword # Python 2.7+
388except ImportError:
390 def iskeyword(unused):
391 '''Not Implemented, C{False} always.
392 '''
393 return False
396def isLatLon(obj, ellipsoidal=None):
397 '''Is B{C{obj}}ect some C{LatLon}?
399 @arg obj: The object (any C{type}).
400 @kwarg ellipsoidal: If C{None}, return the type of any C{LatLon},
401 if C{True}, only an ellipsoidal C{LatLon type}
402 or if C{False}, only a spherical C{LatLon type}.
404 @return: C{type(B{obj}} if a C{LatLon} of the required type, C{False}
405 if a C{LatLon} of an other type or {None} otherwise.
406 '''
407 if ellipsoidal is not None:
408 try:
409 return obj.ellipsoidalLatLon if ellipsoidal else obj.sphericalLatLon
410 except AttributeError:
411 return None
412 return isinstanceof(obj, _MODS.latlonBase.LatLonBase)
415def islistuple(obj, minum=0):
416 '''Is B{C{obj}}ect a C{list} or C{tuple} with non-zero length?
418 @arg obj: The object (any C{type}).
419 @kwarg minum: Minimal C{len} required C({int}).
421 @return: C{True} if a C{list} or C{tuple} with C{len} at
422 least B{C{minum}}, C{False} otherwise.
423 '''
424 return isinstance(obj, _list_tuple_types) and len(obj) >= minum
427def isNvector(obj, ellipsoidal=None):
428 '''Is B{C{obj}}ect some C{Nvector}?
430 @arg obj: The object (any C{type}).
431 @kwarg ellipsoidal: If C{None}, return the type of any C{Nvector},
432 if C{True}, only an ellipsoidal C{Nvector type}
433 or if C{False}, only a spherical C{Nvector type}.
435 @return: C{type(B{obj}} if an C{Nvector} of the required type, C{False}
436 if an C{Nvector} of an other type or {None} otherwise.
437 '''
438 if ellipsoidal is not None:
439 try:
440 return obj.ellipsoidalNvector if ellipsoidal else obj.sphericalNvector
441 except AttributeError:
442 return None
443 return isinstanceof(obj, _MODS.nvectorBase.NvectorBase)
446def isodd(x):
447 '''Is B{C{x}} odd?
449 @arg x: Value (C{scalar}).
451 @return: C{True} if odd, C{False} otherwise.
452 '''
453 return bool(int(x) & 1) # == bool(int(x) % 2)
456def isscalar(obj, both=False):
457 '''Is B{C{obj}}ect an C{int} or integer C{float} value?
459 @arg obj: The object (any C{type}).
460 @kwarg both: If C{True}, check L{Fsum} and L{Fsum2Tuple}
461 residuals.
463 @return: C{True} if C{int}, C{float} or C{Fsum/-2Tuple}
464 with zero residual, C{False} otherwise.
465 '''
466 if isinstance(obj, _Scalars):
467 return not isbool(obj) # exclude bool
468 elif both and _MODS.fsums._isFsum_2Tuple(obj):
469 return bool(obj.residual == 0)
470 return False
473def issequence(obj, *excls):
474 '''Is B{C{obj}}ect some sequence type?
476 @arg obj: The object (any C{type}).
477 @arg excls: Classes to exclude (C{type}), all positional.
479 @note: Excluding C{tuple} implies excluding C{namedtuple}.
481 @return: C{True} if a sequence, C{False} otherwise.
482 '''
483 return isinstance(obj, _Seqs) and not (excls and isinstance(obj, excls))
486def isstr(obj):
487 '''Is B{C{obj}}ect some string type?
489 @arg obj: The object (any C{type}).
491 @return: C{True} if a C{str}, C{bytes}, ...,
492 C{False} otherwise.
493 '''
494 return isinstance(obj, _Strs)
497def issubclassof(Sub, *Supers):
498 '''Is B{C{Sub}} a class and sub-class of some other class(es)?
500 @arg Sub: The sub-class (C{Class}).
501 @arg Supers: One or more C(super) classes (C{Class}).
503 @return: C{True} if a sub-class of any B{C{Supers}}, C{False}
504 if not (C{bool}) or C{None} if not a class or if no
505 B{C{Supers}} are given or none of those are a class.
506 '''
507 if isclass(Sub):
508 t = tuple(S for S in Supers if isclass(S))
509 if t:
510 return bool(issubclass(Sub, t)) # built-in
511 return None
514def itemsorted(adict, *items_args, **asorted_reverse):
515 '''Return the items of C{B{adict}} sorted I{alphabetically,
516 case-insensitively} and in I{ascending} order.
518 @arg items_args: Optional positional argument(s) for method
519 C{B{adict}.items(B*{items_args})}.
520 @kwarg asorted_reverse: Use C{B{asorted}=False} for I{alphabetical,
521 case-sensitive} sorting and C{B{reverse}=True} for
522 sorting in C{descending} order.
523 '''
524 def _ins(item): # functools.cmp_to_key
525 k, v = item
526 return k.lower()
528 def _reverse_key(asorted=True, reverse=False):
529 return dict(reverse=reverse, key=_ins if asorted else None)
531 items = adict.items(*items_args) if items_args else adict.items()
532 return sorted(items, **_reverse_key(**asorted_reverse))
535def len2(items):
536 '''Make built-in function L{len} work for generators, iterators,
537 etc. since those can only be started exactly once.
539 @arg items: Generator, iterator, list, range, tuple, etc.
541 @return: 2-Tuple C{(n, items)} of the number of items (C{int})
542 and the items (C{list} or C{tuple}).
543 '''
544 if not isinstance(items, _Seqs): # NOT hasattr(items, '__len__'):
545 items = list(items)
546 return len(items), items
549def map1(fun1, *xs): # XXX map_
550 '''Call a single-argument function to each B{C{xs}}
551 and return a C{tuple} of results.
553 @arg fun1: 1-Arg function (C{callable}).
554 @arg xs: Arguments (C{any positional}).
556 @return: Function results (C{tuple}).
557 '''
558 return tuple(map(fun1, xs))
561def map2(fun, *xs):
562 '''Like Python's B{C{map}} but returning a C{tuple} of results.
564 Unlike Python 2's built-in L{map}, Python 3+ L{map} returns a
565 L{map} object, an iterator-like object which generates the
566 results only once. Converting the L{map} object to a tuple
567 maintains the Python 2 behavior.
569 @arg fun: Function (C{callable}).
570 @arg xs: Arguments (C{all positional}).
572 @return: Function results (C{tuple}).
573 '''
574 return tuple(map(fun, *xs))
577def neg(x, neg0=None):
578 '''Negate C{x} and optionally, negate C{0.0} and C{-0.0}.
580 @kwarg neg0: Defines the return value for zero C{B{x}}: if C{None}
581 return C{0.0}, if C{True} return C{NEG0 if B{x}=0.0}
582 and C{0.0 if B{x}=NEG0} or if C{False} return C{B{x}}
583 I{as-is} (C{bool} or C{None}).
585 @return: C{-B{x} if B{x} else 0.0, NEG0 or B{x}}.
586 '''
587 return (-x) if x else (
588 _0_0 if neg0 is None else (
589 x if not neg0 else (
590 _0_0 if signBit(x) else _MODS.constants.
591 NEG0))) # PYCHOK indent
594def neg_(*xs):
595 '''Negate all C{xs} with L{neg}.
597 @return: A C{map(neg, B{xs})}.
598 '''
599 return map(neg, xs)
602def _neg0(x):
603 '''(INTERNAL) Return C{NEG0 if x < 0 else _0_0},
604 unlike C{_copysign_0_0} which returns C{_N_0_0}.
605 '''
606 return _MODS.constants.NEG0 if x < 0 else _0_0
609def _req_d_by(where, **name):
610 '''(INTERNAL) Get the fully qualified name.
611 '''
612 m = _MODS.named
613 n = m._name__(**name)
614 m = m.modulename(where, prefixed=True)
615 if n:
616 m = _DOT_(m, n)
617 return _SPACE_(_required_, _by_, m)
620def _reverange(n, stop=-1, step=-1):
621 '''(INTERNAL) Reversed range yielding C{n-1, n-1-step, ..., stop+1}.
622 '''
623 return range(n - 1, stop, step)
626def signBit(x):
627 '''Return C{signbit(B{x})}, like C++.
629 @return: C{True} if C{B{x} < 0} or C{NEG0} (C{bool}).
630 '''
631 return x < 0 or _MODS.constants.isneg0(x)
634def _signOf(x, ref): # in .fsums
635 '''(INTERNAL) Return the sign of B{C{x}} versus B{C{ref}}.
636 '''
637 return (-1) if x < ref else (+1 if x > ref else 0)
640def signOf(x):
641 '''Return sign of C{x} as C{int}.
643 @return: -1, 0 or +1 (C{int}).
644 '''
645 try:
646 s = x.signOf() # Fsum instance?
647 except AttributeError:
648 s = _signOf(x, 0)
649 return s
652def splice(iterable, n=2, **fill):
653 '''Split an iterable into C{n} slices.
655 @arg iterable: Items to be spliced (C{list}, C{tuple}, ...).
656 @kwarg n: Number of slices to generate (C{int}).
657 @kwarg fill: Optional fill value for missing items.
659 @return: A generator for each of B{C{n}} slices,
660 M{iterable[i::n] for i=0..n}.
662 @raise TypeError: Invalid B{C{n}}.
664 @note: Each generated slice is a C{tuple} or a C{list},
665 the latter only if the B{C{iterable}} is a C{list}.
667 @example:
669 >>> from pygeodesy import splice
671 >>> a, b = splice(range(10))
672 >>> a, b
673 ((0, 2, 4, 6, 8), (1, 3, 5, 7, 9))
675 >>> a, b, c = splice(range(10), n=3)
676 >>> a, b, c
677 ((0, 3, 6, 9), (1, 4, 7), (2, 5, 8))
679 >>> a, b, c = splice(range(10), n=3, fill=-1)
680 >>> a, b, c
681 ((0, 3, 6, 9), (1, 4, 7, -1), (2, 5, 8, -1))
683 >>> tuple(splice(list(range(9)), n=5))
684 ([0, 5], [1, 6], [2, 7], [3, 8], [4])
686 >>> splice(range(9), n=1)
687 <generator object splice at 0x0...>
688 '''
689 if not isint(n):
690 raise _TypeError(n=n)
692 t = _xiterablen(iterable)
693 if not isinstance(t, _list_tuple_types):
694 t = tuple(t)
696 if n > 1:
697 if fill:
698 fill = _xkwds_get1(fill, fill=MISSING)
699 if fill is not MISSING:
700 m = len(t) % n
701 if m > 0: # same type fill
702 t = t + type(t)((fill,) * (n - m))
703 for i in range(n):
704 # XXX t[i::n] chokes PyChecker
705 yield t[slice(i, None, n)]
706 else:
707 yield t # 1 slice, all
710def _splituple(strs, *sep_splits): # in .mgrs, ...
711 '''(INTERNAL) Split a C{comma}- or C{whitespace}-separated
712 string into a C{tuple} of stripped C{str}ings.
713 '''
714 t = (strs.split(*sep_splits) if sep_splits else
715 strs.replace(_COMMA_, _SPACE_).split()) if strs else ()
716 return tuple(s.strip() for s in t if s)
719def unsigned0(x):
720 '''Unsign if C{0.0}.
722 @return: C{B{x}} if B{C{x}} else C{0.0}.
723 '''
724 return x if x else _0_0
727def _xcopy(obj, deep=False):
728 '''(INTERNAL) Copy an object, shallow or deep.
730 @arg obj: The object to copy (any C{type}).
731 @kwarg deep: If C{True}, make a deep, otherwise
732 a shallow copy (C{bool}).
734 @return: The copy of B{C{obj}}.
735 '''
736 return _deepcopy(obj) if deep else _copy(obj)
739def _xcoverage(where, *required): # in .__main__ # PYCHOK no cover
740 '''(INTERNAL) Import C{coverage} and check required version.
741 '''
742 try:
743 _xpackages(_xcoverage)
744 import coverage
745 except ImportError as x:
746 raise _xImportError(x, where)
747 return _xversion(coverage, where, *required)
750def _xdup(obj, deep=False, **items):
751 '''(INTERNAL) Duplicate an object, replacing some attributes.
753 @arg obj: The object to copy (any C{type}).
754 @kwarg deep: If C{True}, copy deep, otherwise shallow (C{bool}).
755 @kwarg items: Attributes to be changed (C{any}).
757 @return: A duplicate of B{C{obj}} with modified
758 attributes, if any B{C{items}}.
760 @raise AttributeError: Some B{C{items}} invalid.
761 '''
762 d = _xcopy(obj, deep=deep)
763 for n, v in items.items():
764 if getattr(d, n, v) != v:
765 setattr(d, n, v)
766 elif not hasattr(d, n):
767 t = _MODS.named.classname(obj)
768 t = _SPACE_(_DOT_(t, n), _invalid_)
769 raise _AttributeError(txt=t, obj=obj, **items)
770# if items:
771# _MODS.props._update_all(d)
772 return d
775def _xgeographiclib(where, *required):
776 '''(INTERNAL) Import C{geographiclib} and check required version.
777 '''
778 try:
779 _xpackages(_xgeographiclib)
780 import geographiclib
781 except ImportError as x:
782 raise _xImportError(x, where, Error=LazyImportError)
783 return _xversion(geographiclib, where, *required)
786def _xImportError(exc, where, Error=_ImportError, **name):
787 '''(INTERNAL) Embellish an C{Lazy/ImportError}.
788 '''
789 t = _req_d_by(where, **name)
790 return Error(_Xstr(exc), txt=t, cause=exc)
793def _xinstanceof(*Types, **names_values):
794 '''(INTERNAL) Check C{Types} of all C{name=value} pairs.
796 @arg Types: One or more classes or types (C{class}), all
797 positional.
798 @kwarg names_values: One or more C{B{name}=value} pairs
799 with the C{value} to be checked.
801 @raise TypeError: One B{C{names_values}} pair is not an
802 instance of any of the B{C{Types}}.
803 '''
804 if not (Types and names_values):
805 raise _xAssertionError(_xinstanceof, *Types, **names_values)
807 for n, v in names_values.items():
808 if not isinstance(v, Types):
809 raise _TypesError(n, v, *Types)
812def _xiterable(obj):
813 '''(INTERNAL) Return C{obj} if iterable, otherwise raise C{TypeError}.
814 '''
815 return obj if isiterable(obj) else _xiterror(obj, _xiterable) # PYCHOK None
818def _xiterablen(obj):
819 '''(INTERNAL) Return C{obj} if iterable with C{__len__}, otherwise raise C{TypeError}.
820 '''
821 return obj if isiterablen(obj) else _xiterror(obj, _xiterablen) # PYCHOK None
824def _xiterror(obj, _xwhich):
825 '''(INTERNAL) Helper for C{_xinterable} and C{_xiterablen}.
826 '''
827 t = _not_(_xwhich.__name__[2:]) # _DUNDER_nameof
828 raise _TypeError(repr(obj), txt=t)
831def _xnumpy(where, *required):
832 '''(INTERNAL) Import C{numpy} and check required version.
833 '''
834 try:
835 _xpackages(_xnumpy)
836 import numpy
837 except ImportError as x:
838 raise _xImportError(x, where)
839 return _xversion(numpy, where, *required)
842def _xor(x, *xs):
843 '''(INTERNAL) Exclusive-or C{x} and C{xs}.
844 '''
845 for x_ in xs:
846 x ^= x_
847 return x
850def _xpackages(_xpkgf):
851 '''(INTERNAL) Check dependency to be excluded.
852 '''
853 if _XPACKAGES: # PYCHOK no cover
854 n = _xpkgf.__name__[2:] # _DUNDER_nameof, less '_x'
855 if n.lower() in _XPACKAGES:
856 E = _PYGEODESY(_xpackages)
857 x = _SPACE_(n, _in_, E)
858 e = _enquote(_getenv(E, NN))
859 raise ImportError(_EQUAL_(x, e))
862def _xscalar(**names_values):
863 '''(INTERNAL) Check all C{name=value} pairs to be C{scalar}.
864 '''
865 for n, v in names_values.items():
866 if not isscalar(v):
867 raise _TypeError(n, v, txt=_not_scalar_)
870def _xscipy(where, *required):
871 '''(INTERNAL) Import C{scipy} and check required version.
872 '''
873 try:
874 _xpackages(_xscipy)
875 import scipy
876 except ImportError as x:
877 raise _xImportError(x, where)
878 return _xversion(scipy, where, *required)
881def _xsubclassof(*Classes, **names_values):
882 '''(INTERNAL) Check (super) class of all C{name=value} pairs.
884 @arg Classes: One or more classes or types (C{class}), all
885 positional.
886 @kwarg names_values: One or more C{B{name}=value} pairs
887 with the C{value} to be checked.
889 @raise TypeError: One B{C{names_values}} pair is not a
890 (sub-)class of any of the B{C{Classes}}.
891 '''
892 if not (Classes and names_values):
893 raise _xAssertionError(_xsubclassof, *Classes, **names_values)
895 for n, v in names_values.items():
896 if not issubclassof(v, *Classes):
897 raise _TypesError(n, v, *Classes)
900def _xversion(package, where, *required, **name):
901 '''(INTERNAL) Check the C{package} version vs B{C{required}}.
902 '''
903 if required:
904 t = _version_info(package)
905 if t[:len(required)] < required:
906 t = _SPACE_(package.__name__, # _DUNDER_nameof
907 _version_, _DOT_(*t),
908 _below_, _DOT_(*required),
909 _req_d_by(where, **name))
910 raise ImportError(t)
911 return package
914def _xzip(*args, **strict): # PYCHOK no cover
915 '''(INTERNAL) Standard C{zip(..., strict=True)}.
916 '''
917 s = _xkwds_get1(strict, strict=True)
918 if s:
919 if _zip is zip: # < (3, 10)
920 t = _MODS.streprs.unstr(_xzip, *args, strict=s)
921 raise _NotImplementedError(t, txt=None)
922 return _zip(*args)
923 return zip(*args)
926if _MODS.sys_version_info2 < (3, 10): # see .errors
927 _zip = zip # PYCHOK exported
928else: # Python 3.10+
930 def _zip(*args):
931 return zip(*args, strict=True)
933_XPACKAGES = _splituple(_getenv(_PYGEODESY(_xpackages), NN).lower()) # test/bases._X_OK
935# **) MIT License
936#
937# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
938#
939# Permission is hereby granted, free of charge, to any person obtaining a
940# copy of this software and associated documentation files (the "Software"),
941# to deal in the Software without restriction, including without limitation
942# the rights to use, copy, modify, merge, publish, distribute, sublicense,
943# and/or sell copies of the Software, and to permit persons to whom the
944# Software is furnished to do so, subject to the following conditions:
945#
946# The above copyright notice and this permission notice shall be included
947# in all copies or substantial portions of the Software.
948#
949# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
950# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
951# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
952# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
953# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
954# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
955# OTHER DEALINGS IN THE SOFTWARE.