Coverage for pygeodesy/internals.py: 87%
236 statements
« prev ^ index » next coverage.py v7.6.0, created at 2024-08-02 18:24 -0400
« prev ^ index » next coverage.py v7.6.0, created at 2024-08-02 18:24 -0400
1# -*- coding: utf-8 -*-
3u'''Mostly INTERNAL functions, except L{machine}, L{print_} and L{printf}.
4'''
5# from pygeodesy.basics import isiterablen # _MODS
6# from pygeodesy.errors import _AttributeError, _error_init, _UnexpectedError, _xError2 # _MODS
7from pygeodesy.interns import NN, _BAR_, _COLON_, _DASH_, _DOT_, _ELLIPSIS_, _EQUALSPACED_, \
8 _immutable_, _NL_, _pygeodesy_, _PyPy__, _python_, _QUOTE1_, \
9 _QUOTE2_, _s_, _SPACE_, _sys, _UNDER_, _utf_8_
10from pygeodesy.interns import _COMMA_, _Python_ # PYCHOK used!
11# from pygeodesy.streprs import anstr, pairs, unstr # _MODS
13import os as _os # in .lazily, ...
14import os.path as _os_path
15# import sys as _sys # from .interns
17_0_0 = 0.0 # PYCHOK in .basics, .constants
18_arm64_ = 'arm64'
19_iOS_ = 'iOS'
20_macOS_ = 'macOS'
21_Windows_ = 'Windows'
24def _dunder_nameof(inst, *dflt):
25 '''(INTERNAL) Get the double_underscore __name__ attr.
26 '''
27 try:
28 return inst.__name__
29 except AttributeError:
30 pass
31 return dflt[0] if dflt else inst.__class__.__name__
34def _dunder_nameof_(*names__): # in .errors._IsnotError
35 '''(INTERNAL) Yield the _dunder_nameof or name.
36 '''
37 return map(_dunder_nameof, names__, names__)
40def _Property_RO(method):
41 '''(INTERNAL) Can't I{recursively} import L{props.property_RO}.
42 '''
43 name = _dunder_nameof(method)
45 def _del(inst, attr): # PYCHOK no cover
46 delattr(inst, attr) # force error
48 def _get(inst, **unused): # PYCHOK 2 vs 3 args
49 try: # to get the cached value immediately
50 v = inst.__dict__[name]
51 except (AttributeError, KeyError):
52 # cache the value in the instance' __dict__
53 inst.__dict__[name] = v = method(inst)
54 return v
56 def _set(inst, val): # PYCHOK no cover
57 setattr(inst, name, val) # force error
59 return property(_get, _set, _del)
62class _MODS_Base(object):
63 '''(INTERNAL) Base-class for C{lazily._ALL_MODS}.
64 '''
65 def __delattr__(self, attr): # PYCHOK no cover
66 self.__dict__.pop(attr, None)
68 def __setattr__(self, attr, value): # PYCHOK no cover
69 m = _MODS.errors
70 t = _EQUALSPACED_(self._DOT_(attr), repr(value))
71 raise m._AttributeError(_immutable_, txt=t)
73 @_Property_RO
74 def bits_machine2(self):
75 '''Get platform 2-list C{[bits, machine]}, I{once}.
76 '''
77 import platform as p
79 m = p.machine() # ARM64, arm64, x86_64, iPhone13,2, etc.
80 m = m.replace(_COMMA_, _UNDER_)
81 if m.lower() == 'x86_64': # PYCHOK on Intel or Rosetta2 ...
82 v = p.mac_ver()[0] # ... and only on macOS ...
83 if v and _version2(v) > (10, 15): # ... 11+ aka 10.16
84 # <https://Developer.Apple.com/forums/thread/659846>
85 # _sysctl_uint('hw.optional.arm64') and \
86 if _sysctl_uint('sysctl.proc_translated'):
87 m = _UNDER_(_arm64_, m) # Apple Si emulating Intel x86-64
88 return [p.architecture()[0], # bits
89 m] # arm64, arm64_x86_64, x86_64, etc.
91 @_Property_RO
92 def ctypes3(self):
93 '''Get 3-tuple C{(ctypes.CDLL, ._dlopen, .util.findlibrary)}, I{once}.
94 '''
95 if _ismacOS():
96 from ctypes import CDLL, DEFAULT_MODE, _dlopen
98 def dlopen(name):
99 return _dlopen(name, DEFAULT_MODE)
100 else: # PYCHOK no cover
101 from ctypes import CDLL
102 dlopen = _passarg
104 from ctypes.util import find_library
105 return CDLL, dlopen, find_library
107 @_Property_RO
108 def ctypes5(self):
109 '''Get 5-tuple C{(ctypes.byref, .c_char_p, .c_size_t, .c_uint, .sizeof)}, I{once}.
110 '''
111 from ctypes import byref, c_char_p, c_size_t, c_uint, sizeof # get_errno
112 return byref, c_char_p, c_size_t, c_uint, sizeof
114 def _DOT_(self, name): # PYCHOK no cover
115 return _DOT_(self.name, name)
117 @_Property_RO
118 def errors(self):
119 '''Get module C{pygeodesy.errors}, I{once}.
120 '''
121 from pygeodesy import errors # DON'T _lazy_import2
122 return errors
124 def ios_ver(self):
125 '''Mimick C{platform.xxx_ver} for C{iOS}.
126 '''
127 try: # Pythonista only
128 from platform import iOS_ver
129 return iOS_ver()
130 except (AttributeError, ImportError):
131 return NN, (NN, NN, NN), NN
133 @_Property_RO
134 def libc(self):
135 '''Load C{libc.dll|dylib}, I{once}.
136 '''
137 return _load_lib('libc')
139 @_Property_RO
140 def name(self):
141 '''Get this name (C{str}).
142 '''
143 return _dunder_nameof(self.__class__)
145 @_Property_RO
146 def nix2(self): # PYCHOK no cover
147 '''Get Linux 2-list C{[distro, version]}, I{once}.
148 '''
149 import platform as p
151 n, v = p.uname()[0], NN
152 if n.lower() == 'linux':
153 try: # use distro only for Linux, not macOS, etc.
154 import distro # <https://PyPI.org/project/distro>
155 _a = _MODS.streprs.anstr
156 v = _a(distro.version()) # first
157 n = _a(distro.id()) # .name()?
158 except (AttributeError, ImportError):
159 pass # v = str(_0_0)
160 n = n.capitalize()
161 return n, v
163 def nix_ver(self): # PYCHOK no cover
164 '''Mimick C{platform.xxx_ver} for C{*nix}.
165 '''
166 _, v = _MODS.nix2
167 t = _version2(v, n=3) if v else (NN, NN, NN)
168 return v, t, machine()
170 @_Property_RO
171 def osversion2(self):
172 '''Get 2-list C{[OS, release]}, I{once}.
173 '''
174 import platform as p
176 _Nix, _ = _MODS.nix2
177 # - mac_ver() returns ('10.12.5', ..., 'x86_64') on
178 # macOS and ('10.3.3', ..., 'iPad4,2') on iOS
179 # - win32_ver is ('XP', ..., 'SP3', ...) on Windows XP SP3
180 # - platform() returns 'Darwin-16.6.0-x86_64-i386-64bit'
181 # on macOS and 'Darwin-16.6.0-iPad4,2-64bit' on iOS
182 # - sys.platform is 'darwin' on macOS, 'ios' on iOS,
183 # 'win32' on Windows and 'cygwin' on Windows/Gygwin
184 # - distro.id() and .name() return 'Darwin' on macOS
185 for n, v in ((_iOS_, _MODS.ios_ver),
186 (_macOS_, p.mac_ver),
187 (_Windows_, p.win32_ver),
188 (_Nix, _MODS.nix_ver),
189 ('Java', p.java_ver),
190 ('uname', p.uname)):
191 v = v()[0]
192 if v and n:
193 break
194 else:
195 n = v = NN # XXX AssertioError?
196 return [n, v]
198 @_Property_RO
199 def Pythonarchine(self):
200 '''Get 3- or 4-list C{[PyPy, Python, bits, machine]}, I{once}.
201 '''
202 v = _sys.version
203 l3 = [_Python_(v)] + self.bits_machine2
204 pypy = _PyPy__(v)
205 if pypy: # PYCHOK no cover
206 l3.insert(0, pypy)
207 return l3
209 @_Property_RO
210 def streprs(self):
211 '''Get module C{pygeodesy.streprs}, I{once}.
212 '''
213 from pygeodesy import streprs # DON'T _lazy_import2
214 return streprs
216 @_Property_RO
217 def version(self):
218 '''Get pygeodesy version, I{once}.
219 '''
220 from pygeodesy import version
221 return version
223_MODS = _MODS_Base() # PYCHOK overwritten by .lazily
226def _caller3(up): # in .lazily, .named
227 '''(INTERNAL) Get 3-tuple C{(caller name, file name, line number)}
228 for the caller B{C{up}} stack frames in the Python call stack.
229 '''
230 # sys._getframe(1) ... 'importlib._bootstrap' line 1032,
231 # may throw a ValueError('call stack not deep enough')
232 f = _sys._getframe(up + 1)
233 c = f.f_code
234 return (c.co_name, # caller name
235 _os_path.basename(c.co_filename), # file name .py
236 f.f_lineno) # line number
239def _dunder_ismain(name):
240 '''(INTERNAL) Return C{name == '__main__'}.
241 '''
242 return name == '__main__'
245def _enquote(strs, quote=_QUOTE2_, white=NN): # in .basics, .solveBase
246 '''(INTERNAL) Enquote a string containing whitespace or replace
247 whitespace by C{white} if specified.
248 '''
249 if strs:
250 t = strs.split()
251 if len(t) > 1:
252 strs = white.join(t if white else (quote, strs, quote))
253 return strs
256def _headof(name):
257 '''(INTERNAL) Get the head name of qualified C{name} or the C{name}.
258 '''
259 i = name.find(_DOT_)
260 return name if i < 0 else name[:i]
263# def _is(a, b): # PYCHOK no cover
264# '''(INTERNAL) C{a is b}? in C{PyPy}
265# '''
266# return (a == b) if _isPyPy() else (a is b)
269def _isAppleM():
270 '''(INTERNAL) Is this C{Apple Silicon}? (C{bool})
271 '''
272 return _ismacOS() and machine().startswith(_arm64_)
275def _isiOS(): # in test/bases.py
276 '''(INTERNAL) Is this C{iOS}? (C{bool})
277 '''
278 return _MODS.osversion2[0] is _iOS_
281def _ismacOS(): # in test/bases.py
282 '''(INTERNAL) Is this C{macOS}? (C{bool})
283 '''
284 return _sys.platform[:6] == 'darwin' and \
285 _MODS.osversion2[0] is _macOS_ # and os.name == 'posix'
288def _isNix(): # in test/bases.py
289 '''(INTERNAL) Is this a C{Linux} distro? (C{str} or L{NN})
290 '''
291 return _MODS.nix2[0]
294def _isPyPy(): # in test/bases.py
295 '''(INTERNAL) Is this C{PyPy}? (C{bool})
296 '''
297 # platform.python_implementation() == 'PyPy'
298 return _MODS.Pythonarchine[0].startswith(_PyPy__)
301def _isWindows(): # in test/bases.py
302 '''(INTERNAL) Is this C{Windows}? (C{bool})
303 '''
304 return _sys.platform[:3] == 'win' and \
305 _MODS.osversion2[0] is _Windows_
308def _load_lib(name):
309 '''(INTERNAL) Load a C{dylib}, B{C{name}} must startwith('lib').
310 '''
311 # macOS 11+ (aka 10.16) no longer provides direct loading of
312 # system libraries. As a result, C{ctypes.util.find_library}
313 # will not find any library, unless previously installed by a
314 # low-level dlopen(name) call (with the library base C{name}).
315 CDLL, dlopen, find_lib = _MODS.ctypes3
317 ns = find_lib(name), name
318 if dlopen is not _passarg: # _ismacOS()
319 ns += (_DOT_(name, 'dylib'),
320 _DOT_(name, 'framework'), _os_path.join(
321 _DOT_(name, 'framework'), name))
322 for n in ns:
323 try:
324 if n and dlopen(n): # pre-load handle
325 lib = CDLL(n) # == ctypes.cdll.LoadLibrary(n)
326 if lib._name: # has a qualified name
327 return lib
328 except (AttributeError, OSError):
329 pass
331 return None # raise OSError
334def machine():
335 '''Return standard C{platform.machine}, but distinguishing Intel I{native}
336 from Intel I{emulation} on Apple Silicon (on macOS only).
338 @return: Machine C{'arm64'} for Apple Silicon I{native}, C{'x86_64'}
339 for Intel I{native}, C{"arm64_x86_64"} for Intel I{emulation},
340 etc. (C{str} with C{comma}s replaced by C{underscore}s).
341 '''
342 return _MODS.bits_machine2[1]
345def _name_version(pkg):
346 '''(INTERNAL) Return C{pskg.__name__ + ' ' + .__version__}.
347 '''
348 return _SPACE_(pkg.__name__, pkg.__version__)
351def _osversion2(sep=NN): # in .lazily, test/bases.versions
352 '''(INTERNAL) Get the O/S name and release as C{2-list} or C{str}.
353 '''
354 l2 = _MODS.osversion2
355 return sep.join(l2) if sep else l2 # 2-list()
358def _passarg(arg):
359 '''(INTERNAL) Helper, no-op.
360 '''
361 return arg
364def _passargs(*args):
365 '''(INTERNAL) Helper, no-op.
366 '''
367 return args
370def _plural(noun, n, nn=NN):
371 '''(INTERNAL) Return C{noun}['s'] or C{NN}.
372 '''
373 return NN(noun, _s_) if n > 1 else (noun if n else nn)
376def print_(*args, **nl_nt_prec_prefix__end_file_flush_sep__kwds): # PYCHOK no cover
377 '''Python 3+ C{print}-like formatting and printing.
379 @arg args: Values to be converted to C{str} and joined by B{C{sep}},
380 all positional.
382 @see: Function L{printf} for further details.
383 '''
384 return printf(NN, *args, **nl_nt_prec_prefix__end_file_flush_sep__kwds)
387def printf(fmt, *args, **nl_nt_prec_prefix__end_file_flush_sep__kwds):
388 '''C{Printf-style} and Python 3+ C{print}-like formatting and printing.
390 @arg fmt: U{Printf-style<https://Docs.Python.org/3/library/stdtypes.html#
391 printf-style-string-formatting>} format specification (C{str}).
392 @arg args: Arguments to be formatted (any C{type}, all positional).
393 @kwarg nl_nt_prec_prefix__end_file_flush_sep__kwds: Optional keyword arguments
394 C{B{nl}=0} for the number of leading blank lines (C{int}), C{B{nt}=0}
395 the number of trailing blank lines (C{int}), C{B{prefix}=NN} to be
396 inserted before the formatted text (C{str}) and Python 3+ C{print}
397 keyword arguments C{B{end}}, C{B{sep}}, C{B{file}} and C{B{flush}}.
398 Any remaining C{B{kwds}} are C{printf-style} name-value pairs to be
399 formatted, I{iff no B{C{args}} are present} using C{B{prec}=6} for
400 the number of decimal digits (C{int}).
402 @return: Number of bytes written.
403 '''
404 b, e, f, fl, p, s, kwds = _print7(**nl_nt_prec_prefix__end_file_flush_sep__kwds)
405 try:
406 if args:
407 t = (fmt % args) if fmt else s.join(map(str, args))
408 elif kwds:
409 t = (fmt % kwds) if fmt else s.join(
410 _MODS.streprs.pairs(kwds, prec=p))
411 else:
412 t = fmt
413 except Exception as x:
414 _E, s = _MODS.errors._xError2(x)
415 unstr = _MODS.streprs.unstr
416 t = unstr(printf, fmt, *args, **nl_nt_prec_prefix__end_file_flush_sep__kwds)
417 raise _E(s, txt=t, cause=x)
418 try:
419 n = f.write(NN(b, t, e))
420 except UnicodeEncodeError: # XXX only Windows
421 t = t.replace('\u2032', _QUOTE1_).replace('\u2033', _QUOTE2_)
422 n = f.write(NN(b, t, e))
423 if fl: # PYCHOK no cover
424 f.flush()
425 return n
428def _print7(nl=0, nt=0, prec=6, prefix=NN, sep=_SPACE_, file=_sys.stdout,
429 end=_NL_, flush=False, **kwds):
430 '''(INTERNAL) Unravel the C{printf} and remaining keyword arguments.
431 '''
432 if nl > 0:
433 prefix = NN(_NL_ * nl, prefix)
434 if nt > 0:
435 end = NN(end, _NL_ * nt)
436 return prefix, end, file, flush, prec, sep, kwds
439def _Pythonarchine(sep=NN): # in .lazily, test/bases.py versions
440 '''(INTERNAL) Get PyPy and Python versions, bits and machine as C{3- or 4-list} or C{str}.
441 '''
442 l3 = _MODS.Pythonarchine
443 return sep.join(l3) if sep else l3 # 3- or 4-list
446def _sizeof(obj):
447 '''(INTERNAL) Recursively size an C{obj}ect.
449 @return: The C{obj} size in bytes (C{int}),
450 ignoring class attributes and
451 counting duplicates only once or
452 C{None}.
454 @note: With C{PyPy}, the size is always C{None}.
455 '''
456 try:
457 _zB = _sys.getsizeof
458 _zD = _zB(None) # some default
459 except TypeError: # PyPy3.10
460 return None
462 _isiterablen = _MODS.basics.isiterablen
464 def _zR(s, iterable):
465 z, _s = 0, s.add
466 for o in iterable:
467 i = id(o)
468 if i not in s:
469 _s(i)
470 z += _zB(o, _zD)
471 if isinstance(o, dict):
472 z += _zR(s, o.keys())
473 z += _zR(s, o.values())
474 elif _isiterablen(o): # not map, ...
475 z += _zR(s, o)
476 else:
477 try: # size instance' attr values only
478 z += _zR(s, o.__dict__.values())
479 except AttributeError: # None, int, etc.
480 pass
481 return z
483 return _zR(set(), (obj,))
486def _sysctl_uint(name):
487 '''(INTERNAL) Get an unsigned int sysctl item by name, use on macOS ONLY!
488 '''
489 libc = _MODS.libc
490 if libc: # <https://StackOverflow.com/questions/759892/python-ctypes-and-sysctl>
491 byref, char_p, size_t, uint, sizeof = _MODS.ctypes5
492 n = name if str is bytes else bytes(name, _utf_8_) # PYCHOK isPython2 = str is bytes
493 u = uint(0)
494 z = size_t(sizeof(u))
495 r = libc.sysctlbyname(char_p(n), byref(u), byref(z), None, size_t(0))
496 else: # could find or load 'libc'
497 r = -2
498 return int(r if r else u.value) # -1 ENOENT error, -2 no libc
501def _tailof(name):
502 '''(INTERNAL) Get the base name of qualified C{name} or the C{name}.
503 '''
504 i = name.rfind(_DOT_) + 1
505 return name[i:] if i > 0 else name
508def _under(name): # PYCHOK in .datums, .auxilats, .ups, .utm, .utmupsBase, ...
509 '''(INTERNAL) Prefix C{name} with an I{underscore}.
510 '''
511 return name if name.startswith(_UNDER_) else NN(_UNDER_, name)
514def _usage(file_py, *args, **opts_help): # in .etm, .geodesici
515 '''(INTERNAL) Build "usage: python -m ..." cmd line for module B{C{file_py}}.
516 '''
517 if opts_help:
519 def _help(alts=(), help=NN, **unused):
520 if alts and help:
521 h = NN(help, _SPACE_).lstrip(_DASH_)
522 for a in alts:
523 if a.startswith(h):
524 return NN(_DASH_, a),
526 def _opts(opts=NN, alts=(), **unused):
527 # opts='T--v-C-R meter-c|i|n|o'
528 d, fmt = NN, _MODS.streprs.Fmt.SQUARE
529 for o in (opts + _BAR_(*alts)).split(_DASH_):
530 if o:
531 yield fmt(NN(d, _DASH_, o.replace(_BAR_, ' | -')))
532 d = NN
533 else:
534 d = _DASH_
536 args = _help(**opts_help) or (tuple(_opts(**opts_help)) + args)
538 u = _COLON_(_dunder_nameof(_usage)[1:], NN)
539 return _SPACE_(u, *_usage_argv(file_py, *args))
542def _usage_argv(argv0, *args):
543 '''(INTERNAL) Return 3-tuple C{(python, '-m', module, *args)}.
544 '''
545 m = _os_path.dirname(argv0).replace(_os.getcwd(), _ELLIPSIS_) \
546 .replace(_os.sep, _DOT_).strip()
547 b, x = _os_path.splitext(_os_path.basename(argv0))
548 if x == '.py' and not _dunder_ismain(b):
549 m = _DOT_(m or _pygeodesy_, b)
550 p = NN(_python_, _sys.version_info[0])
551 return (p, '-m', _enquote(m)) + args
554def _version2(version, n=2):
555 '''(INTERNAL) Split C{B{version} str} into a C{1-, 2- or 3-tuple} of C{int}s.
556 '''
557 t = _version_ints(version.split(_DOT_, 2))
558 if len(t) < n:
559 t += (0,) * n
560 return t[:n]
563def _version_info(package): # in .Base.karney, .basics
564 '''(INTERNAL) Get the C{package.__version_info__} as a 2- or
565 3-tuple C{(major, minor, revision)} if C{int}s.
566 '''
567 try:
568 return _version_ints(package.__version_info__)
569 except AttributeError:
570 return _version2(package.__version__.strip(), n=3)
573def _version_ints(vs):
574 # helper for _version2 and _version_info above
576 def _ints(vs):
577 for v in vs:
578 try:
579 yield int(v.strip())
580 except (TypeError, ValueError):
581 pass
583 return tuple(_ints(vs))
586def _versions(sep=_SPACE_):
587 '''(INTERNAL) Get pygeodesy, PyPy and Python versions, bits, machine and OS as C{7- or 8-list} or C{str}.
588 '''
589 l7 = [_pygeodesy_, _MODS.version] + _Pythonarchine() + _osversion2()
590 return sep.join(l7) if sep else l7 # 5- or 6-list
593__all__ = tuple(map(_dunder_nameof, (machine, print_, printf)))
594__version__ = '24.08.01'
596if _dunder_ismain(__name__): # PYCHOK no cover
598 from pygeodesy import _isfrozen, isLazy
600 print_(*(_versions(sep=NN) + ['_isfrozen', _isfrozen,
601 'isLazy', isLazy]))
603# **) MIT License
604#
605# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.
606#
607# Permission is hereby granted, free of charge, to any person obtaining a
608# copy of this software and associated documentation files (the "Software"),
609# to deal in the Software without restriction, including without limitation
610# the rights to use, copy, modify, merge, publish, distribute, sublicense,
611# and/or sell copies of the Software, and to permit persons to whom the
612# Software is furnished to do so, subject to the following conditions:
613#
614# The above copyright notice and this permission notice shall be included
615# in all copies or substantial portions of the Software.
616#
617# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
618# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
619# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
620# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
621# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
622# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
623# OTHER DEALINGS IN THE SOFTWARE.