1

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

3

4 u'''Some, basic definitions, functions and dependencies.

5

6 Use env variable C{PYGEODESY_XPACKAGES} to avoid import of dependencies

7 C{geographiclib}, C{numpy} and/or C{scipy}. Set C{PYGEODESY_XPACKAGES}

8 to a comma-separated list of package names to be excluded from import.

9'''

10# make sure int/int division yields float quotient

11 from __future__ import division

12 division = 1 / 2 # .albers, .azimuthal, .constants, etc., .utily

13 if not division:

14 raise ImportError('%s 1/2 == %s' % ('division', division))

15 del division

16

17# from pygeodesy.cartesianBase import CartesianBase # _MODS

18# from pygeodesy.constants import isneg0, NEG0 # _MODS

19 from pygeodesy.errors import _AttributeError, _ImportError, _NotImplementedError, \

20 _TypeError, _TypesError, _ValueError, _xAssertionError, \

21 _xkwds_get1

22# from pygeodesy.fsums import _isFsum_2Tuple # _MODS

23 from pygeodesy.internals import _0_0, _enquote, _getenv, _passarg, _PYGEODESY, \

24 _version_info

25 from 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

29 from 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

34

35 from copy import copy as _copy, deepcopy as _deepcopy

36 from math import copysign as _copysign

37# import inspect as _inspect # _MODS

38

39__all__ = _ALL_LAZY.basics

40__version__ = '24.10.14'

41

42_below_ = 'below'

43_list_tuple_types = (list, tuple)

44_required_ = 'required'

45

46 try: # Luciano Ramalho, "Fluent Python", O'Reilly, 2016 p. 395, 2022 p. 577+

47 from numbers import Integral as _Ints, Real as _Scalars # .units

48 except 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

54

55 try:

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

65 except ImportError:

66 _Sequence = tuple # immutable for .points._Basequence

67 _Seqs = list, _Sequence # range for function len2 below

68

69 try:

70 _Bytes = unicode, bytearray # PYCHOK in .internals

71 _Strs = basestring, str # XXX str == bytes

72 str2ub = ub2str = _passarg # avoids UnicodeDecodeError

73

74 def _Xstr(exc): # PYCHOK no cover

75 '''I{Invoke only with caught ImportError} B{C{exc}}.

76

77 C{... "can't import name _distributor_init" ...}

78

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

91

92 except NameError: # Python 3+

93 from pygeodesy.interns import _utf_8_

94

95 _Bytes = bytes, bytearray # in .internals

96 _Strs = str, # tuple

97 _Xstr = str

98

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

105

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

112

113

114 def _args_kwds_count2(func, exelf=True):

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: # PYCHOK no cover

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

137

138

139 def _args_kwds_names(func, splast=False):

140 '''(INTERNAL) Get a C{func}'s args and kwds names, including

141 C{self} for methods.

142

143 @kwarg splast: If C{True}, split the last keyword argument

144 at UNDERscores (C{bool}).

145

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)

162

163

164 def clips(sb, limit=50, white=NN, length=False):

165 '''Clip a string to the given length limit.

166

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}).

171

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

184

185

186 def copysign0(x, y):

187 '''Like C{math.copysign(x, y)} except C{zero}, I{unsigned}.

188

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)

193

194

195 def copytype(x, y):

196 '''Return the value of B{x} as C{type} of C{y}.

197

198 @return: C{type(B{y})(B{x})}.

199 '''

200 return type(y)(x if x else _0_0)

201

202

203 def _enumereverse(iterable):

204 '''(INTERNAL) Reversed C{enumberate}.

205 '''

206 for j in _reverange(len(iterable)):

207 yield j, iterable[j]

208

209

210 def halfs2(str2):

211 '''Split a string in 2 halfs.

212

213 @arg str2: String to split (C{str}).

214

215 @return: 2-Tuple C{(_1st, _2nd)} half (C{str}).

216

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:]

223

224

225 def int1s(x):

226 '''Count the number of 1-bits in an C{int}, I{unsigned}.

227

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_)

235

236

237 def isbool(obj):

238 '''Is B{C{obj}}ect a C{bool}ean?

239

240 @arg obj: The object (any C{type}).

241

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)

246

247 assert not (isbool(1) or isbool(0) or isbool(None)) # PYCHOK 2

248

249

250 def isCartesian(obj, ellipsoidal=None):

251 '''Is B{C{obj}}ect some C{Cartesian}?

252

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}.

257

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)

267

268

269 def 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)

273

274

275 def iscomplex(obj, both=False):

276 '''Is B{C{obj}}ect a C{complex} or complex literal C{str}?

277

278 @arg obj: The object (any C{type}).

279 @kwarg both: If C{True}, check complex C{str} (C{bool}).

280

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

288

289

290 def isDEPRECATED(obj):

291 '''Is B{C{obj}}ect a C{DEPRECATED} class, method or function?

292

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

301

302

303 def isfloat(obj, both=False):

304 '''Is B{C{obj}}ect a C{float} or float literal C{str}?

305

306 @arg obj: The object (any C{type}).

307 @kwarg both: If C{True}, check float C{str} (C{bool}).

308

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

316

317

318 try:

319 isidentifier = str.isidentifier # Python 3, must be str

320 except AttributeError: # Python 2-

321

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())

328

329

330 def isinstanceof(obj, *Classes):

331 '''Is B{C{obj}}ect an instance of one of the C{Classes}?

332

333 @arg obj: The object (any C{type}).

334 @arg Classes: One or more classes (C{Class}).

335

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

340

341

342 def isint(obj, both=False):

343 '''Is B{C{obj}}ect an C{int} or integer C{float} value?

344

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}).

348

349 @return: C{True} if C{int} or I{integer} C{float}

350 or L{Fsum}, C{False} otherwise.

351

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

363

364

365 def isiterable(obj):

366 '''Is B{C{obj}}ect C{iterable}?

367

368 @arg obj: The object (any C{type}).

369

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

374

375

376 def isiterablen(obj):

377 '''Is B{C{obj}}ect C{iterable} and has C{len}gth?

378

379 @arg obj: The object (any C{type}).

380

381 @return: C{True} if C{iterable} with C{len}gth, C{False} otherwise.

382 '''

383 return hasattr(obj, '__len__') and hasattr(obj, '__getitem__')

384

385

386 try:

387 from keyword import iskeyword # Python 2.7+

388 except ImportError:

389

390 def iskeyword(unused):

391 '''Not Implemented, C{False} always.

392 '''

393 return False

394

395

396 def isLatLon(obj, ellipsoidal=None):

397 '''Is B{C{obj}}ect some C{LatLon}?

398

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}.

403

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)

413

414

415 def islistuple(obj, minum=0):

416 '''Is B{C{obj}}ect a C{list} or C{tuple} with non-zero length?

417

418 @arg obj: The object (any C{type}).

419 @kwarg minum: Minimal C{len} required C({int}).

420

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

425

426

427 def isNvector(obj, ellipsoidal=None):

428 '''Is B{C{obj}}ect some C{Nvector}?

429

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}.

434

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)

444

445

446 def isodd(x):

447 '''Is B{C{x}} odd?

448

449 @arg x: Value (C{scalar}).

450

451 @return: C{True} if odd, C{False} otherwise.

452 '''

453 return bool(int(x) & 1) # == bool(int(x) % 2)

454

455

456 def isscalar(obj, both=False):

457 '''Is B{C{obj}}ect an C{int} or integer C{float} value?

458

459 @arg obj: The object (any C{type}).

460 @kwarg both: If C{True}, check L{Fsum} and L{Fsum2Tuple}

461 residuals.

462

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

471

472

473 def issequence(obj, *excls):

474 '''Is B{C{obj}}ect some sequence type?

475

476 @arg obj: The object (any C{type}).

477 @arg excls: Classes to exclude (C{type}), all positional.

478

479 @note: Excluding C{tuple} implies excluding C{namedtuple}.

480

481 @return: C{True} if a sequence, C{False} otherwise.

482 '''

483 return isinstance(obj, _Seqs) and not (excls and isinstance(obj, excls))

484

485

486 def isstr(obj):

487 '''Is B{C{obj}}ect some string type?

488

489 @arg obj: The object (any C{type}).

490

491 @return: C{True} if a C{str}, C{bytes}, ...,

492 C{False} otherwise.

493 '''

494 return isinstance(obj, _Strs)

495

496

497 def issubclassof(Sub, *Supers):

498 '''Is B{C{Sub}} a class and sub-class of some other class(es)?

499

500 @arg Sub: The sub-class (C{Class}).

501 @arg Supers: One or more C(super) classes (C{Class}).

502

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

512

513

514 def 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.

517

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()

527

528 def _reverse_key(asorted=True, reverse=False):

529 return dict(reverse=reverse, key=_ins if asorted else None)

530

531 items = adict.items(*items_args) if items_args else adict.items()

532 return sorted(items, **_reverse_key(**asorted_reverse))

533

534

535 def len2(items):

536 '''Make built-in function L{len} work for generators, iterators,

537 etc. since those can only be started exactly once.

538

539 @arg items: Generator, iterator, list, range, tuple, etc.

540

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

547

548

549 def map1(fun1, *xs): # XXX map_

550 '''Call a single-argument function to each B{C{xs}}

551 and return a C{tuple} of results.

552

553 @arg fun1: 1-Arg function (C{callable}).

554 @arg xs: Arguments (C{any positional}).

555

556 @return: Function results (C{tuple}).

557 '''

558 return tuple(map(fun1, xs))

559

560

561 def map2(fun, *xs):

562 '''Like Python's B{C{map}} but returning a C{tuple} of results.

563

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.

568

569 @arg fun: Function (C{callable}).

570 @arg xs: Arguments (C{all positional}).

571

572 @return: Function results (C{tuple}).

573 '''

574 return tuple(map(fun, *xs))

575

576

577 def neg(x, neg0=None):

578 '''Negate C{x} and optionally, negate C{0.0} and C{-0.0}.

579

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}).

584

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

592

593

594 def neg_(*xs):

595 '''Negate all C{xs} with L{neg}.

596

597 @return: A C{map(neg, B{xs})}.

598 '''

599 return map(neg, xs)

600

601

602 def _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

607

608

609 def _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)

618

619

620 def _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)

624

625

626 def signBit(x):

627 '''Return C{signbit(B{x})}, like C++.

628

629 @return: C{True} if C{B{x} < 0} or C{NEG0} (C{bool}).

630 '''

631 return x < 0 or _MODS.constants.isneg0(x)

632

633

634 def _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)

638

639

640 def signOf(x):

641 '''Return sign of C{x} as C{int}.

642

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

650

651

652 def splice(iterable, n=2, **fill):

653 '''Split an iterable into C{n} slices.

654

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.

658

659 @return: A generator for each of B{C{n}} slices,

660 M{iterable[i::n] for i=0..n}.

661

662 @raise TypeError: Invalid B{C{n}}.

663

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}.

666

667 @example:

668

669 >>> from pygeodesy import splice

670

671 >>> a, b = splice(range(10))

672 >>> a, b

673 ((0, 2, 4, 6, 8), (1, 3, 5, 7, 9))

674

675 >>> a, b, c = splice(range(10), n=3)

676 >>> a, b, c

677 ((0, 3, 6, 9), (1, 4, 7), (2, 5, 8))

678

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))

682

683 >>> tuple(splice(list(range(9)), n=5))

684 ([0, 5], [1, 6], [2, 7], [3, 8], [4])

685

686 >>> splice(range(9), n=1)

687 <generator object splice at 0x0...>

688 '''

689 if not isint(n):

690 raise _TypeError(n=n)

691

692 t = _xiterablen(iterable)

693 if not isinstance(t, _list_tuple_types):

694 t = tuple(t)

695

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

708

709

710 def _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)

717

718

719 def unsigned0(x):

720 '''Unsign if C{0.0}.

721

722 @return: C{B{x}} if B{C{x}} else C{0.0}.

723 '''

724 return x if x else _0_0

725

726

727 def _xcopy(obj, deep=False):

728 '''(INTERNAL) Copy an object, shallow or deep.

729

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}).

733

734 @return: The copy of B{C{obj}}.

735 '''

736 return _deepcopy(obj) if deep else _copy(obj)

737

738

739 def _xcoverage(where, *required):

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)

748

749

750 def _xdup(obj, deep=False, **items):

751 '''(INTERNAL) Duplicate an object, replacing some attributes.

752

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}).

756

757 @return: A duplicate of B{C{obj}} with modified

758 attributes, if any B{C{items}}.

759

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

773

774

775 def _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)

784

785

786 def _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)

791

792

793 def _xinstanceof(*Types, **names_values):

794 '''(INTERNAL) Check C{Types} of all C{name=value} pairs.

795

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.

800

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)

806

807 for n, v in names_values.items():

808 if not isinstance(v, Types):

809 raise _TypesError(n, v, *Types)

810

811

812 def _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

816

817

818 def _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

822

823

824 def _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)

829

830

831 def _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)

840

841

842 def _xor(x, *xs):

843 '''(INTERNAL) Exclusive-or C{x} and C{xs}.

844 '''

845 for x_ in xs:

846 x ^= x_

847 return x

848

849

850 def _xpackages(_xpkg):

851 '''(INTERNAL) Check dependency to be excluded.

852 '''

853 n = _xpkg.__name__[2:] # _DUNDER_nameof, less '_x'

854 if n in _XPACKAGES: # n.lower() in _XPACKAGES

855 E = _PYGEODESY(_xpackages)

856 x = _SPACE_(n, _in_, E)

857 e = _enquote(_getenv(E, NN))

858 raise ImportError(_EQUAL_(x, e))

859

860

861 def _xscalar(**names_values):

862 '''(INTERNAL) Check all C{name=value} pairs to be C{scalar}.

863 '''

864 for n, v in names_values.items():

865 if not isscalar(v):

866 raise _TypeError(n, v, txt=_not_scalar_)

867

868

869 def _xscipy(where, *required):

870 '''(INTERNAL) Import C{scipy} and check required version.

871 '''

872 try:

873 _xpackages(_xscipy)

874 import scipy

875 except ImportError as x:

876 raise _xImportError(x, where)

877 return _xversion(scipy, where, *required)

878

879

880 def _xsubclassof(*Classes, **names_values):

881 '''(INTERNAL) Check (super) class of all C{name=value} pairs.

882

883 @arg Classes: One or more classes or types (C{class}), all

884 positional.

885 @kwarg names_values: One or more C{B{name}=value} pairs

886 with the C{value} to be checked.

887

888 @raise TypeError: One B{C{names_values}} pair is not a

889 (sub-)class of any of the B{C{Classes}}.

890 '''

891 if not (Classes and names_values):

892 raise _xAssertionError(_xsubclassof, *Classes, **names_values)

893

894 for n, v in names_values.items():

895 if not issubclassof(v, *Classes):

896 raise _TypesError(n, v, *Classes)

897

898

899 def _xversion(package, where, *required, **name):

900 '''(INTERNAL) Check the C{package} version vs B{C{required}}.

901 '''

902 if required:

903 t = _version_info(package)

904 if t[:len(required)] < required:

905 t = _SPACE_(package.__name__, # _DUNDER_nameof

906 _version_, _DOT_(*t),

907 _below_, _DOT_(*required),

908 _req_d_by(where, **name))

909 raise ImportError(t)

910 return package

911

912

913 def _xzip(*args, **strict): # PYCHOK no cover

914 '''(INTERNAL) Standard C{zip(..., strict=True)}.

915 '''

916 s = _xkwds_get1(strict, strict=True)

917 if s:

918 if _zip is zip: # < (3, 10)

919 t = _MODS.streprs.unstr(_xzip, *args, strict=s)

920 raise _NotImplementedError(t, txt=None)

921 return _zip(*args)

922 return zip(*args)

923

924

925 if _MODS.sys_version_info2 < (3, 10): # see .errors

926 _zip = zip # PYCHOK exported

927 else: # Python 3.10+

928

929 def _zip(*args):

930 return zip(*args, strict=True)

931

932_XPACKAGES = _splituple(_getenv(_PYGEODESY(_xpackages), NN).lower()) # test/bases._X_OK

933

934# **) MIT License

935#

936# Copyright (C) 2016-2024 -- mrJean1 at Gmail -- All Rights Reserved.

937#

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

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

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

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

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

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

944#

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

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

947#

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

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

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

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

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

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

954# OTHER DEALINGS IN THE SOFTWARE.