Coverage for pygeodesy/internals.py: 92%

265 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-04 12:01 -0400

1 

2# -*- coding: utf-8 -*- 

3 

4u'''Mostly INTERNAL functions, except L{machine}, L{print_} and L{printf}. 

5''' 

6# from pygeodesy.basics import isiterablen, ubstr # _MODS 

7# from pygeodesy.errors import _AttributeError, _error_init, _UnexpectedError, _xError2 # _MODS 

8from pygeodesy.interns import _BAR_, _COLON_, _DASH_, _DMAIN_, _DOT_, _ELLIPSIS_, _EQUALSPACED_, \ 

9 _immutable_, _NL_, NN, _pygeodesy_, _PyPy__, _python_, _QUOTE1_, \ 

10 _QUOTE2_, _s_, _SPACE_, _sys, _UNDER_ 

11from pygeodesy.interns import _COMMA_, _Python_ # PYCHOK used! 

12# from pygeodesy.streprs import anstr, pairs, unstr # _MODS 

13 

14# import os # _MODS 

15# import os.path # _MODS 

16# import sys as _sys # from .interns 

17 

18_0_0 = 0.0 # PYCHOK in .basics, .constants 

19_100_0 = 100.0 # in .constants 

20_arm64_ = 'arm64' 

21_iOS_ = 'iOS' 

22_macOS_ = 'macOS' 

23_SIsecs = 'fs', 'ps', 'ns', 'us', 'ms', 'sec' # reversed 

24_Windows_ = 'Windows' 

25 

26 

27def typename(obj, *dflt): 

28 '''Get the C{obj.__name__}, the C{dflt} or its outer C{type.__name__} or C{NN} (C{str}). 

29 ''' 

30 try: 

31 return obj.__name__ 

32 except (AttributeError, ImportError): # LazyImportError 

33 pass 

34 return dflt[0] if dflt else typename(type(obj), NN) 

35 

36 

37def _Property_RO(method): 

38 '''(INTERNAL) Can't import L{props.Property_RO}, I{recursively}. 

39 ''' 

40 name = typename(method) 

41 

42 def _del(inst, *unused): # PYCHOK no cover 

43 inst.__dict__.pop(name, None) 

44 

45 def _get(inst, *unused): # PYCHOK 2 vs 3 args 

46 try: # to get the cached value immediately 

47 v = inst.__dict__[name] 

48 except (AttributeError, KeyError): 

49 # cache the value in the instance' __dict__ 

50 inst.__dict__[name] = v = method(inst) 

51 return v 

52 

53 def _set(inst, val): # PYCHOK no cover 

54 setattr(inst, name, val) # force error 

55 

56 return property(_get, _set, _del) 

57 

58 

59class _MODS_Base(object): 

60 '''(INTERNAL) Base-class for C{lazily._ALL_MODS}. 

61 ''' 

62 def __delattr__(self, attr): # PYCHOK no cover 

63 self.__dict__.pop(attr, None) 

64 

65 def __setattr__(self, attr, value): # PYCHOK no cover 

66 e = _MODS.errors 

67 n = _DOT_(self.name, attr) 

68 t = _EQUALSPACED_(n, repr(value)) 

69 raise e._AttributeError(_immutable_, txt=t) 

70 

71 @_Property_RO 

72 def basics(self): 

73 '''Get module C{pygeodesy.basics}, I{once}. 

74 ''' 

75 from pygeodesy import basics as b # DON'T _lazy_import2 

76 return b 

77 

78 @_Property_RO 

79 def bits_machine2(self): 

80 '''Get platform 2-list C{[bits, machine]}, I{once}. 

81 ''' 

82 import platform as p 

83 m = p.machine() # ARM64, arm64, x86_64, iPhone13,2, etc. 

84 m = m.replace(_COMMA_, _UNDER_) 

85 if m.lower() == 'x86_64': # PYCHOK on Intel or Rosetta2 ... 

86 v = p.mac_ver()[0] # ... and only on macOS ... 

87 if v and _version2(v) > (10, 15): # ... 11+ aka 10.16 

88 # <https://Developer.Apple.com/forums/thread/659846> 

89 # _sysctl_uint('hw.optional.arm64') and \ 

90 if _sysctl_uint('sysctl.proc_translated'): 

91 m = _UNDER_(_arm64_, m) # Apple Si emulating Intel x86-64 

92 return [p.architecture()[0], # bits 

93 m] # arm64, arm64_x86_64, x86_64, etc. 

94 

95 @_Property_RO 

96 def ctypes3(self): 

97 '''Get C{ctypes.CDLL}, C{find_library} and C{dlopen}, I{once}. 

98 ''' 

99 import ctypes as c 

100 from ctypes.util import find_library as f 

101 

102 def dlopen(name): # on macOS only 

103 return c._dlopen(name, c.DEFAULT_MODE) 

104 

105 return c.CDLL, f, (dlopen if _ismacOS() else None) 

106 

107 @_Property_RO 

108 def errors(self): 

109 '''Get module C{pygeodesy.errors}, I{once}. 

110 ''' 

111 from pygeodesy import errors as e # DON'T _lazy_import2 

112 return e 

113 

114 @_Property_RO 

115 def inspect(self): # in .basics 

116 '''Get module C{inspect}, I{once}. 

117 ''' 

118 import inspect as i 

119 return i 

120 

121 def ios_ver(self): 

122 '''Mimick C{platform.xxx_ver} for C{iOS}. 

123 ''' 

124 try: # Pythonista only 

125 from platform import iOS_ver 

126 t = iOS_ver() 

127 except (AttributeError, ImportError): 

128 t = NN, (NN, NN, NN), NN 

129 return t 

130 

131 @_Property_RO 

132 def name(self): 

133 '''Get this name (C{str}). 

134 ''' 

135 return typename(self.__class__) 

136 

137 @_Property_RO 

138 def nix2(self): # PYCHOK no cover 

139 '''Get Linux 2-tuple C{(distro, version)}, I{once}. 

140 ''' 

141 from platform import uname 

142 v, n = NN, uname()[0] # [0] == .system 

143 if n.lower() == 'linux': 

144 try: # use distro only on Linux, not macOS, etc. 

145 import distro # <https://PyPI.org/project/distro> 

146 _a = _MODS.streprs.anstr 

147 v = _a(distro.version()) # first 

148 n = _a(distro.id()) # .name()? 

149 except (AttributeError, ImportError): 

150 pass # v = str(_0_0) 

151 n = n.capitalize() 

152 return n, v 

153 

154 def nix_ver(self): # PYCHOK no cover 

155 '''Mimick C{platform.xxx_ver} for C{*nix}. 

156 ''' 

157 _, v = _MODS.nix2 

158 t = _version2(v, n=3) if v else (NN, NN, NN) 

159 return v, t, machine() 

160 

161 @_Property_RO 

162 def os(self): 

163 '''Get module C{os}, I{once}. 

164 ''' 

165 import os as o 

166 import os.path 

167 return o 

168 

169 @_Property_RO 

170 def osversion2(self): 

171 '''Get 2-list C{[OS, release]}, I{once}. 

172 ''' 

173 import platform as p 

174 _Nix, _ = _MODS.nix2 

175 # - mac_ver() returns ('10.12.5', ..., 'x86_64') on 

176 # macOS and ('10.3.3', ..., 'iPad4,2') on iOS 

177 # - win32_ver is ('XP', ..., 'SP3', ...) on Windows XP SP3 

178 # - platform() returns 'Darwin-16.6.0-x86_64-i386-64bit' 

179 # on macOS and 'Darwin-16.6.0-iPad4,2-64bit' on iOS 

180 # - sys.platform is 'darwin' on macOS, 'ios' on iOS, 

181 # 'win32' on Windows and 'cygwin' on Windows/Gygwin 

182 # - distro.id() and .name() return 'Darwin' on macOS 

183 for n, v in ((_iOS_, _MODS.ios_ver), 

184 (_macOS_, p.mac_ver), 

185 (_Windows_, p.win32_ver), 

186 (_Nix, _MODS.nix_ver), 

187 ('Java', p.java_ver), 

188 ('uname', p.uname)): 

189 v = v()[0] 

190 if v and n: 

191 break 

192 else: 

193 n = v = NN # XXX AssertionError? 

194 return [n, v] 

195 

196 @_Property_RO 

197 def _Popen_kwds2(self): 

198 '''(INTERNAL) Get C{subprocess.Popen} and C{-kwds}. 

199 ''' 

200 import subprocess as s 

201 kwds = dict(creationflags=0, # executable=sys.executable, shell=True, 

202 stdin=s.PIPE, stdout=s.PIPE, stderr=s.STDOUT) 

203 if _MODS.sys_version_info2 > (3, 6): 

204 kwds.update(text=True) 

205 return s.Popen, kwds 

206 

207 @_Property_RO 

208 def Pythonarchine(self): 

209 '''Get 3- or 4-list C{[PyPy, Python, bits, machine]}, I{once}. 

210 ''' 

211 v = _sys.version 

212 l3 = [_Python_(v)] + _MODS.bits_machine2 

213 pypy = _PyPy__(v) 

214 if pypy: # PYCHOK no cover 

215 l3.insert(0, pypy) 

216 return l3 

217 

218 @_Property_RO 

219 def streprs(self): 

220 '''Get module C{pygeodesy.streprs}, I{once}. 

221 ''' 

222 from pygeodesy import streprs as s # DON'T _lazy_import2 

223 return s 

224 

225 @_Property_RO 

226 def sys_version_info2(self): 

227 '''Get C{sys.version_inf0[:2], I{once}. 

228 ''' 

229 return _sys.version_info[:2] 

230 

231 @_Property_RO 

232 def version(self): 

233 '''Get pygeodesy version, I{once}. 

234 ''' 

235 from pygeodesy import version as v 

236 return v 

237 

238_MODS = _MODS_Base() # PYCHOK overwritten by .lazily 

239 

240 

241def _caller3(up, base=True): # in .lazily, .named 

242 '''(INTERNAL) Get 3-tuple C{(caller name, file name, line number)} 

243 for the caller B{C{up}} frames back in the Python call stack. 

244 

245 @kwarg base: Use C{B{base}=False} for the fully-qualified file 

246 name, otherwise the base (module) name (C{bool}). 

247 ''' 

248 f = None 

249 _b = _MODS.os.path.basename if base else _passarg 

250 try: 

251 f = _sys._getframe(up + 1) # == inspect.stack()[up + 1][0] 

252 t = _MODS.inspect.getframeinfo(f) 

253 t = t.function, _b(t.filename), t.lineno 

254# or ... 

255 # f = _sys._getframe(up + 1) 

256 # c = f.f_code 

257 # t = (c.co_name, # caller name 

258 # _b(c.co_filename), # file name .py 

259 # f.f_lineno) # line number 

260# or ... 

261 # t = _MODS.inspect.stack()[up + 1] # (frame, filename, lineno, function, ...) 

262 # t = t[3], _b(t[1]), t[2] 

263 except (AttributeError, IndexError, ValueError): 

264 # sys._getframe(1) ... 'importlib._bootstrap' line 1032, 

265 # may throw a ValueError('call stack not deep enough') 

266 t = NN, NN, 0 

267 finally: 

268 del f # break ref cycle 

269 return t 

270 

271 

272def _enquote(strs, quote=_QUOTE2_, white=NN): # in .basics, .solveBase 

273 '''(INTERNAL) Enquote a string containing whitespace or replace 

274 whitespace by C{white} if specified. 

275 ''' 

276 if strs: 

277 t = strs.split() 

278 if len(t) > 1: 

279 strs = white.join(t if white else (quote, strs, quote)) 

280 return strs 

281 

282 

283def _envPYGEODESY(which, dflt=NN): 

284 '''(INTERNAL) Return an C{PYGEODESY_...} ENV value or C{dflt}. 

285 ''' 

286 return _getenv(_PYGEODESY_ENV(which), dflt) 

287 

288 

289def _fper(p, q, per=_100_0, prec=1): 

290 '''Format a percentage C{B{p} * B{per} / B{q}} (C{str}). 

291 ''' 

292 return '%.*f%%' % (prec, (float(p) * per / float(q))) 

293 

294 

295_getenv = _MODS.os.getenv # PYCHOK in .lazily, ... 

296 

297 

298def _headof(name): 

299 '''(INTERNAL) Get the head name of qualified C{name} or the C{name}. 

300 ''' 

301 i = name.find(_DOT_) 

302 return name if i < 0 else name[:i] 

303 

304 

305# def _is(a, b): # PYCHOK no cover 

306# '''(INTERNAL) C{a is b}? in C{PyPy} 

307# ''' 

308# return (a == b) if _isPyPy() else (a is b) 

309 

310 

311def _isAppleSi(): # PYCHOK no cover 

312 '''(INTERNAL) Is this C{macOS on Apple Silicon}? (C{bool}) 

313 ''' 

314 return _ismacOS() and machine().startswith(_arm64_) 

315 

316 

317def _isiOS(): # in test/bases 

318 '''(INTERNAL) Is this C{iOS}? (C{bool}) 

319 ''' 

320 return _MODS.osversion2[0] is _iOS_ 

321 

322 

323def _ismacOS(): # in test/bases 

324 '''(INTERNAL) Is this C{macOS}? (C{bool}) 

325 ''' 

326 return _sys.platform[:6] == 'darwin' and \ 

327 _MODS.osversion2[0] is _macOS_ # and _MODS.os.name == 'posix' 

328 

329 

330def _isNix(): # in test/bases 

331 '''(INTERNAL) Is this a C{Linux} distro? (C{str} or L{NN}) 

332 ''' 

333 return _MODS.nix2[0] 

334 

335 

336def _isPyChOK(): # PYCHOK no cover 

337 '''(INTERNAL) Is C{PyChecker} running? (C{bool}) 

338 ''' 

339 # .../pychecker/checker.py --limit 0 --stdlib pygeodesy/<mod>/<name>.py 

340 return _sys.argv[0].endswith('/pychecker/checker.py') or \ 

341 bool(_envPYGEODESY('PYCHOK')) 

342 

343 

344def _isPyPy(): # in test/bases 

345 '''(INTERNAL) Is this C{PyPy}? (C{bool}) 

346 ''' 

347 # platform.python_implementation() == 'PyPy' 

348 return _MODS.Pythonarchine[0].startswith(_PyPy__) 

349 

350 

351def _isWindows(): # in test/bases 

352 '''(INTERNAL) Is this C{Windows}? (C{bool}) 

353 ''' 

354 return _sys.platform[:3] == 'win' and \ 

355 _MODS.osversion2[0] is _Windows_ 

356 

357 

358def _load_lib(name): 

359 '''(INTERNAL) Load a C{dylib}, B{C{name}} must startwith('lib'). 

360 ''' 

361 CDLL, find_lib, dlopen = _MODS.ctypes3 

362 ns = find_lib(name), name 

363 if dlopen: 

364 # macOS 11+ (aka 10.16) no longer provides direct loading of 

365 # system libraries. As a result, C{ctypes.util.find_library} 

366 # will not find any library, unless previously installed by a 

367 # low-level dlopen(name) call (with the library base C{name}). 

368 ns += (_DOT_(name, 'dylib'), 

369 _DOT_(name, 'framework'), _MODS.os.path.join( 

370 _DOT_(name, 'framework'), name)) 

371 else: # not macOS 

372 dlopen = _passarg # no-op 

373 

374 for n in ns: 

375 try: 

376 if n and dlopen(n): # pre-load handle 

377 lib = CDLL(n) # == ctypes.cdll.LoadLibrary(n) 

378 if lib._name: # has a qualified name 

379 return lib 

380 except (AttributeError, OSError): 

381 pass 

382 

383 return None # raise OSError 

384 

385 

386def machine(): 

387 '''Return standard C{platform.machine}, but distinguishing Intel I{native} 

388 from Intel I{emulation} on Apple Silicon (on macOS only). 

389 

390 @return: Machine C{'arm64'} for Apple Silicon I{native}, C{'x86_64'} 

391 for Intel I{native}, C{"arm64_x86_64"} for Intel I{emulation}, 

392 etc. (C{str} with C{comma}s replaced by C{underscore}s). 

393 ''' 

394 return _MODS.bits_machine2[1] 

395 

396 

397def _name_version(pkg): 

398 '''(INTERNAL) Return C{pkg.__name__ + ' ' + .__version__}. 

399 ''' 

400 return _SPACE_(typename(pkg), pkg.__version__) # _DVERSION_ 

401 

402 

403def _osversion2(sep=NN): # in .lazily, test/bases.versions 

404 '''(INTERNAL) Get the O/S name and release as C{2-list} or C{str}. 

405 ''' 

406 l2 = _MODS.osversion2 

407 return sep.join(l2) if sep else l2 # 2-list() 

408 

409 

410def _passarg(arg): 

411 '''(INTERNAL) Helper, no-op. 

412 ''' 

413 return arg 

414 

415 

416def _passargs(*args): 

417 '''(INTERNAL) Helper, no-op. 

418 ''' 

419 return args 

420 

421 

422def _plural(noun, n, nn=NN): 

423 '''(INTERNAL) Return C{noun}['s'] or C{NN}. 

424 ''' 

425 return NN(noun, _s_) if n > 1 else (noun if n else nn) 

426 

427 

428def _popen2(cmd, stdin=None): # in .mgrs, .solveBase, .testMgrs 

429 '''(INTERNAL) Invoke C{B{cmd} tuple} and return 2-tuple C{(std, status)} 

430 with all C{stdout/-err} output, I{stripped} and C{int} exit status. 

431 ''' 

432 _Popen, kwds = _MODS._Popen_kwds2 

433 p = _Popen(cmd, **kwds) # PYCHOK kwArgs 

434 r = p.communicate(stdin)[0] # stdout + NL + stderr 

435 return _MODS.basics.ub2str(r).strip(), p.returncode 

436 

437 

438def print_(*args, **nl_nt_prec_prefix__end_file_flush_sep__kwds): # PYCHOK no cover 

439 '''Python 3+ C{print}-like formatting and printing. 

440 

441 @arg args: Values to be converted to C{str} and joined by B{C{sep}}, 

442 all positional. 

443 

444 @see: Function L{printf} for further details. 

445 ''' 

446 return printf(NN, *args, **nl_nt_prec_prefix__end_file_flush_sep__kwds) 

447 

448 

449def printf(fmt, *args, **nl_nt_prec_prefix__end_file_flush_sep__kwds): 

450 '''C{Printf-style} and Python 3+ C{print}-like formatting and printing. 

451 

452 @arg fmt: U{Printf-style<https://Docs.Python.org/3/library/stdtypes.html# 

453 printf-style-string-formatting>} format specification (C{str}). 

454 @arg args: Arguments to be formatted (any C{type}, all positional). 

455 @kwarg nl_nt_prec_prefix__end_file_flush_sep__kwds: Optional keyword arguments 

456 C{B{nl}=0} for the number of leading blank lines (C{int}), C{B{nt}=0} 

457 the number of trailing blank lines (C{int}), C{B{prefix}=NN} to be 

458 inserted before the formatted text (C{str}) and Python 3+ C{print} 

459 keyword arguments C{B{end}}, C{B{sep}}, C{B{file}} and C{B{flush}}. 

460 Any remaining C{B{kwds}} are C{printf-style} name-value pairs to be 

461 formatted, I{iff no B{C{args}} are present} using C{B{prec}=6} for 

462 the number of decimal digits (C{int}). 

463 

464 @return: Number of bytes written. 

465 ''' 

466 b, e, f, fl, p, s, kwds = _print7(**nl_nt_prec_prefix__end_file_flush_sep__kwds) 

467 try: 

468 if args: 

469 t = (fmt % args) if fmt else s.join(map(str, args)) 

470 elif kwds: 

471 t = (fmt % kwds) if fmt else s.join( 

472 _MODS.streprs.pairs(kwds, prec=p)) 

473 else: 

474 t = fmt 

475 except Exception as x: 

476 _E, s = _MODS.errors._xError2(x) 

477 unstr = _MODS.streprs.unstr 

478 t = unstr(printf, fmt, *args, **nl_nt_prec_prefix__end_file_flush_sep__kwds) 

479 raise _E(s, txt=t, cause=x) 

480 try: 

481 n = f.write(NN(b, t, e)) 

482 except UnicodeEncodeError: # XXX only Windows 

483 t = t.replace('\u2032', _QUOTE1_).replace('\u2033', _QUOTE2_) 

484 n = f.write(NN(b, t, e)) 

485 if fl: # PYCHOK no cover 

486 f.flush() 

487 return n 

488 

489 

490def _print7(nl=0, nt=0, prec=6, prefix=NN, sep=_SPACE_, file=_sys.stdout, 

491 end=_NL_, flush=False, **kwds): 

492 '''(INTERNAL) Unravel the C{printf} and remaining keyword arguments. 

493 ''' 

494 if nl > 0: 

495 prefix = NN(_NL_ * nl, prefix) 

496 if nt > 0: 

497 end = NN(end, _NL_ * nt) 

498 return prefix, end, file, flush, prec, sep, kwds 

499 

500 

501def _PYGEODESY_ENV(which): 

502 '''(INTERNAL) Return an ENV C{str} C{PYGEODESY_...}. 

503 ''' 

504 return _UNDER_(_pygeodesy_, typename(which, which)).upper() 

505 

506 

507def _Pythonarchine(sep=NN): # in .lazily, test/bases versions 

508 '''(INTERNAL) Get PyPy and Python versions, bits and machine as C{3- or 4-list} or C{str}. 

509 ''' 

510 l3 = _MODS.Pythonarchine 

511 return sep.join(l3) if sep else l3 # 3- or 4-list 

512 

513 

514def _secs2str(secs): # in .geoids, ../test/bases 

515 '''Convert a time in C{secs} to C{str}. 

516 ''' 

517 if secs < _100_0: 

518 unit = len(_SIsecs) - 1 

519 while 0 < secs < 1 and unit > 0: 

520 secs *= 1e3 # _1000_0 

521 unit -= 1 

522 t = '%.3f %s' % (secs, _SIsecs[unit]) 

523 else: 

524 m, s = divmod(secs, 60) 

525 if m < 60: 

526 t = '%d:%06.3f' % (int(m), s) 

527 else: 

528 h, m = divmod(int(m), 60) 

529 t = '%d:%02d:%06.3f' % (h, m, s) 

530 return t 

531 

532 

533def _sizeof(obj, deep=True): 

534 '''(INTERNAL) Recursively size an C{obj}ect. 

535 

536 @kwarg deep: If C{True}, include the size of all 

537 C{.__dict__.values()} (C{bool}). 

538 

539 @return: The C{obj} size in bytes (C{int}), ignoring 

540 class attributes and counting instances only 

541 once or C{None}. 

542 

543 @note: With C{PyPy}, the returned size is always C{None}. 

544 ''' 

545 try: 

546 _zB = _sys.getsizeof 

547 _zD = _zB(None) # some default 

548 except TypeError: # PyPy3.10 

549 return None 

550 

551 b = _MODS.basics 

552 _isiterablen = b.isiterablen 

553 _Str_Bytes = b._Strs + b._Bytes # + (range, map) 

554 

555 def _zR(s, iterable): 

556 z, _s = 0, s.add 

557 for o in iterable: 

558 i = id(o) 

559 if i not in s: 

560 _s(i) 

561 z += _zB(o, _zD) 

562 if isinstance(o, dict): 

563 z += _zR(s, o.keys()) 

564 z += _zR(s, o.values()) 

565 elif _isiterablen(o) and not \ 

566 isinstance(o, _Str_Bytes): 

567 z += _zR(s, o) 

568 elif deep: 

569 try: # size instance' attr values only 

570 z += _zR(s, o.__dict__.values()) 

571 except AttributeError: # None, int, etc. 

572 pass 

573 return z 

574 

575 return _zR(set(), (obj,)) 

576 

577 

578def _sysctl_uint(name): 

579 '''(INTERNAL) Get an C{unsigned int sysctl} item by name, I{ONLY on macOS!} 

580 ''' 

581 libc = _load_lib('libc') if _ismacOS() else None 

582 if libc: # <https://StackOverflow.com/questions/759892/python-ctypes-and-sysctl> 

583 import ctypes as c 

584 n = c.c_char_p(_MODS.basics.str2ub(name)) # bytes(name, _utf_8_) 

585 u = c.c_uint(0) 

586 z = c.c_size_t(c.sizeof(u)) 

587 r = libc.sysctlbyname(n, c.byref(u), c.byref(z), None, c.c_size_t(0)) # PYCHOK attr 

588 else: # not macOS or couldn't find or load 'libc'= 

589 r = -2 

590 return int(r if r else u.value) # -1 ENOENT error, -2 no libc or not macOS 

591 

592 

593def _tailof(name): 

594 '''(INTERNAL) Get the base name of qualified C{name} or the C{name}. 

595 ''' 

596 i = name.rfind(_DOT_) + 1 

597 return name[i:] if i > 0 else name 

598 

599 

600def _under(name): # PYCHOK in .datums, .auxilats, .geodesicw, .ups, .utm, .utmupsBase, ... 

601 '''(INTERNAL) Prefix C{name} with an I{underscore}. 

602 ''' 

603 return name if name.startswith(_UNDER_) else NN(_UNDER_, name) 

604 

605 

606def _usage(file_py, *args, **opts_help): # in .etm, .geodesici # PYCHOK no cover 

607 '''(INTERNAL) Build "usage: python -m ..." cmd line for module B{C{file_py}}. 

608 ''' 

609 if opts_help: 

610 

611 def _help(alts=(), help=NN, **unused): 

612 if alts and help: 

613 h = NN(help, _SPACE_).lstrip(_DASH_) 

614 for a in alts: 

615 if a.startswith(h): 

616 return NN(_DASH_, a), 

617 

618 def _opts(opts=NN, alts=(), **unused): 

619 # opts='T--v-C-R meter-c|i|n|o' 

620 d, fmt = NN, _MODS.streprs.Fmt.SQUARE 

621 for o in (opts + _BAR_(*alts)).split(_DASH_): 

622 if o: 

623 yield fmt(NN(d, _DASH_, o.replace(_BAR_, ' | -'))) 

624 d = NN 

625 else: 

626 d = _DASH_ 

627 

628 args = _help(**opts_help) or (tuple(_opts(**opts_help)) + args) 

629 

630 u = _COLON_(typename(_usage)[1:], NN) 

631 return _SPACE_(u, *_usage_argv(file_py, *args)) 

632 

633 

634def _usage_argv(argv0, *args): 

635 '''(INTERNAL) Return 3-tuple C{(python, '-m', module, *args)}. 

636 ''' 

637 o = _MODS.os 

638 m = o.path.dirname(argv0) 

639 m = m.replace(o.getcwd(), _ELLIPSIS_) \ 

640 .replace(o.sep, _DOT_).strip() 

641 b = o.path.basename(argv0) 

642 b, x = o.path.splitext(b) 

643 if x == '.py' and b != _DMAIN_: 

644 m = _DOT_(m or _pygeodesy_, b) 

645 p = NN(_python_, _MODS.sys_version_info2[0]) 

646 return (p, '-m', _enquote(m)) + args 

647 

648 

649def _version2(version, n=2): 

650 '''(INTERNAL) Split C{B{version} str} into a C{1-, 2- or 3-tuple} of C{int}s. 

651 ''' 

652 t = _version_ints(version.split(_DOT_, 2)) 

653 if len(t) < n: 

654 t += (0,) * n 

655 return t[:n] 

656 

657 

658def _version_info(package): # in .basics, .karney._kWrapped.Math 

659 '''(INTERNAL) Get the C{package.__version_info__} as a 2- or 

660 3-tuple C{(major, minor, revision)} if C{int}s. 

661 ''' 

662 try: 

663 return _version_ints(package.__version_info__) 

664 except AttributeError: 

665 return _version2(package.__version__.strip(), n=3) 

666 

667 

668def _version_ints(vs): 

669 # helper for _version2 and _version_info above 

670 

671 def _ints(vs): 

672 for v in vs: 

673 try: 

674 yield int(v.strip()) 

675 except (TypeError, ValueError): 

676 pass 

677 

678 return tuple(_ints(vs)) 

679 

680 

681def _versions(sep=_SPACE_): 

682 '''(INTERNAL) Get pygeodesy, PyPy and Python versions, bits, machine and OS as C{8- or 9-list} or C{str}. 

683 ''' 

684 l7 = [_pygeodesy_, _MODS.version] + _Pythonarchine() + _osversion2() 

685 return sep.join(l7) if sep else l7 # 5- or 6-list 

686 

687 

688__all__ = tuple(map(typename, (machine, print_, printf, typename))) 

689__version__ = '25.04.14' 

690 

691if __name__ == _DMAIN_: 

692 

693 def _main(): 

694 from pygeodesy import _isfrozen, isLazy 

695 

696 print_(*(_versions(sep=NN) + ['_isfrozen', _isfrozen, 

697 'isLazy', isLazy])) 

698 

699 _main() 

700 

701# % python3 -m pygeodesy.internals 

702# pygeodesy 25.4.14 Python 3.13.2 64bit arm64 macOS 15.4 _isfrozen False isLazy 1 

703 

704# **) MIT License 

705# 

706# Copyright (C) 2016-2025 -- mrJean1 at Gmail -- All Rights Reserved. 

707# 

708# Permission is hereby granted, free of charge, to any person obtaining a 

709# copy of this software and associated documentation files (the "Software"), 

710# to deal in the Software without restriction, including without limitation 

711# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

712# and/or sell copies of the Software, and to permit persons to whom the 

713# Software is furnished to do so, subject to the following conditions: 

714# 

715# The above copyright notice and this permission notice shall be included 

716# in all copies or substantial portions of the Software. 

717# 

718# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

719# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

720# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

721# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

722# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

723# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

724# OTHER DEALINGS IN THE SOFTWARE.