1

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

3

4 u'''Errors, exceptions, exception formatting and exception chaining.

5

6 Error, exception classes and functions to format PyGeodesy errors,

7 including the setting of I{exception chaining} in Python 3+.

8

9 By default, I{exception chaining} is turned I{off}. To enable I{exception

10 chaining}, use command line option C{python -X dev} I{OR} set env variable

11 C{PYTHONDEVMODE=1} or to any non-empyty string I{OR} set env variable

12 C{PYGEODESY_EXCEPTION_CHAINING=std} or to any non-empty string.

13'''

14

15 from pygeodesy.interns import MISSING, NN, _a_, _an_, _and_, _clip_, \

16 _COLON_, _COLONSPACE_, _COMMASPACE_, _datum_, \

17 _ellipsoidal_, _EQUAL_, _incompatible_, _invalid_, \

18 _len_, _name_, _no_, _not_, _or_, _SPACE_, \

19 _specified_, _UNDER_, _value_, _vs_, _with_

20 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, _getenv, \

21 _pairs, _PYTHON_X_DEV

22

23__all__ = _ALL_LAZY.errors # _ALL_DOCS('_InvalidError', '_IsnotError') _UNDER

24__version__ = '23.03.09'

25

26_box_ = 'box'

27_default_ = 'default'

28_kwargs_ = 'kwargs' # XXX _kwds_?

29_limiterrors = True # imported by .formy

30_multiple_ = 'multiple'

31_name_value_ = repr('name=value')

32_rangerrors = True # imported by .dms

33_region_ = 'region'

34_vs__ = _SPACE_(NN, _vs_, NN)

35

36 try:

37 _exception_chaining = None # not available

38 _ = Exception().__cause__ # Python 3+ exception chaining

39

40 if _PYTHON_X_DEV or _getenv('PYGEODESY_EXCEPTION_CHAINING', NN): # == _std_

41 _exception_chaining = True # turned on, std

42 raise AttributeError # allow exception chaining

43

44 _exception_chaining = False # turned off

45

46 def _error_cause(inst, cause=None):

47 '''(INTERNAL) Set or avoid Python 3+ exception chaining.

48

49 Setting C{inst.__cause__ = None} is equivalent to syntax

50 C{raise Error(...) from None} to avoid exception chaining.

51

52 @arg inst: An error instance (I{caught} C{Exception}).

53 @kwarg cause: A previous error instance (I{caught} C{Exception})

54 or C{None} to avoid exception chaining.

55

56 @see: Alex Martelli, et.al., "Python in a Nutshell", 3rd Ed., page 163,

57 O'Reilly, 2017, U{PEP-3134<https://www.Python.org/dev/peps/pep-3134>},

58 U{here<https://StackOverflow.com/questions/17091520/how-can-i-more-

59 easily-suppress-previous-exceptions-when-i-raise-my-own-exception>}

60 and U{here<https://StackOverflow.com/questions/1350671/

61 inner-exception-with-traceback-in-python>}.

62 '''

63 inst.__cause__ = cause # None, no exception chaining

64 return inst

65

66 except AttributeError: # Python 2+

67

68 def _error_cause(inst, **unused): # PYCHOK expected

69 return inst # no-op

70

71

72 class _AssertionError(AssertionError):

73 '''(INTERNAL) Format an C{AssertionError} with/-out exception chaining.

74 '''

75 def __init__(self, *args, **kwds):

76 _error_init(AssertionError, self, args, **kwds)

77

78

79 class _AttributeError(AttributeError):

80 '''(INTERNAL) Format an C{AttributeError} with/-out exception chaining.

81 '''

82 def __init__(self, *args, **kwds):

83 _error_init(AttributeError, self, args, **kwds)

84

85

86 class _ImportError(ImportError):

87 '''(INTERNAL) Format an C{ImportError} with/-out exception chaining.

88 '''

89 def __init__(self, *args, **kwds):

90 _error_init(ImportError, self, args, **kwds)

91

92

93 class _IndexError(IndexError):

94 '''(INTERNAL) Format an C{IndexError} with/-out exception chaining.

95 '''

96 def __init__(self, *args, **kwds):

97 _error_init(IndexError, self, args, **kwds)

98

99

100 class _KeyError(KeyError):

101 '''(INTERNAL) Format a C{KeyError} with/-out exception chaining.

102 '''

103 def __init__(self, *args, **kwds): # txt=_invalid_

104 _error_init(KeyError, self, args, **kwds)

105

106

107 class _NameError(NameError):

108 '''(INTERNAL) Format a C{NameError} with/-out exception chaining.

109 '''

110 def __init__(self, *args, **kwds):

111 _error_init(NameError, self, args, **kwds)

112

113

114 class _NotImplementedError(NotImplementedError):

115 '''(INTERNAL) Format a C{NotImplementedError} with/-out exception chaining.

116 '''

117 def __init__(self, *args, **kwds):

118 _error_init(NotImplementedError, self, args, **kwds)

119

120

121 class _OverflowError(OverflowError):

122 '''(INTERNAL) Format an C{OverflowError} with/-out exception chaining.

123 '''

124 def __init__(self, *args, **kwds): # txt=_invalid_

125 _error_init(OverflowError, self, args, **kwds)

126

127

128 class _TypeError(TypeError):

129 '''(INTERNAL) Format a C{TypeError} with/-out exception chaining.

130 '''

131 def __init__(self, *args, **kwds):

132 _error_init(TypeError, self, args, fmt_name_value='type(%s) (%r)', **kwds)

133

134

135 class _TypesError(_TypeError):

136 '''(INTERNAL) Format a C{TypeError} with/-out exception chaining.

137 '''

138 def __init__(self, name, value, *Types, **kwds):

139 t = _not_(_an(_or(*(t.__name__ for t in Types))))

140 _TypeError.__init__(self, name, value, txt=t, **kwds)

141

142

143 class _ValueError(ValueError):

144 '''(INTERNAL) Format a C{ValueError} with/-out exception chaining.

145 '''

146 def __init__(self, *args, **kwds): # ..., cause=None, txt=_invalid_, ...

147 _error_init(ValueError, self, args, **kwds)

148

149

150 class _ZeroDivisionError(ZeroDivisionError):

151 '''(INTERNAL) Format a C{ZeroDivisionError} with/-out exception chaining.

152 '''

153 def __init__(self, *args, **kwds):

154 _error_init(ZeroDivisionError, self, args, **kwds)

155

156

157 class ClipError(_ValueError):

158 '''Clip box or clip region issue.

159 '''

160 def __init__(self, *name_n_corners, **txt_cause):

161 '''New L{ClipError}.

162

163 @arg name_n_corners: Either just a name (C{str}) or

164 name, number, corners (C{str},

165 C{int}, C{tuple}).

166 @kwarg txt_cause: Optional C{B{txt}=str} explanation

167 of the error and C{B{cause}=None}

168 for exception chaining.

169 '''

170 if len(name_n_corners) == 3:

171 t, n, v = name_n_corners

172 n = _SPACE_(t, _clip_, (_box_ if n == 2 else _region_))

173 name_n_corners = n, v

174 _ValueError.__init__(self, *name_n_corners, **txt_cause)

175

176

177 class CrossError(_ValueError):

178 '''Error raised for zero or near-zero vectorial cross products,

179 occurring for coincident or colinear points, paths or bearings.

180 '''

181 pass

182

183

184 class IntersectionError(_ValueError): # in .ellipsoidalBaseDI, .formy, ...

185 '''Error raised for path or circle intersection issues.

186 '''

187 def __init__(self, *args, **kwds):

188 '''New L{IntersectionError}.

189 '''

190 if args:

191 _ValueError.__init__(self, _SPACE_(*args), **kwds)

192 else:

193 _ValueError.__init__(self, **kwds)

194

195

196 class LenError(_ValueError): # in .ecef, .fmath, .heights, .iters, .named

197 '''Error raised for mis-matching C{len} values.

198 '''

199 def __init__(self, where, **lens_txt): # txt=None

200 '''New L{LenError}.

201

202 @arg where: Object with C{.__name__} attribute

203 (C{class}, C{method}, or C{function}).

204 @kwarg lens_txt: Two or more C{name=len(name)} pairs

205 (C{keyword arguments}).

206 '''

207 def _ns_vs_txt_x(cause=None, txt=_invalid_, **kwds):

208 ns, vs = zip(*itemsorted(kwds)) # unzip

209 return ns, vs, txt, cause

210

211 ns, vs, txt, x = _ns_vs_txt_x(**lens_txt)

212 ns = _COMMASPACE_.join(ns)

213 t = _MODS.streprs.Fmt.PAREN(where.__name__, ns)

214 vs = _vs__.join(map(str, vs))

215 t = _SPACE_(t, _len_, vs)

216 _ValueError.__init__(self, t, txt=txt, cause=x)

217

218

219 class LimitError(_ValueError):

220 '''Error raised for lat- or longitudinal deltas exceeding

221 the B{C{limit}} in functions L{pygeodesy.equirectangular} and

222 L{pygeodesy.equirectangular_} and several C{nearestOn*} and

223 C{simplify*} functions or methods.

224 '''

225 pass

226

227

228 class MGRSError(_ValueError):

229 '''Military Grid Reference System (MGRS) parse or other L{Mgrs} issue.

230 '''

231 pass

232

233

234 class NumPyError(_ValueError):

235 '''Error raised for C{NumPy} issues.

236 '''

237 pass

238

239

240 class ParseError(_ValueError): # in .dms, .elevations, .utmupsBase

241 '''Error parsing degrees, radians or several other formats.

242 '''

243 pass

244

245

246 class PointsError(_ValueError): # in .clipy, .frechet, ...

247 '''Error for an insufficient number of points.

248 '''

249 pass

250

251

252 class RangeError(_ValueError): # in .dms, .ellipsoidalBase, .geoids, .units, .ups, .utm, .utmups

253 '''Error raised for lat- or longitude values outside the B{C{clip}}, B{C{clipLat}},

254 B{C{clipLon}} or B{C{limit}} range in function L{pygeodesy.clipDegrees},

255 L{pygeodesy.clipRadians}, L{pygeodesy.parse3llh}, L{pygeodesy.parseDMS},

256 L{pygeodesy.parseDMS2} or L{pygeodesy.parseRad}.

257

258 @see: Function L{pygeodesy.rangerrors}.

259 '''

260 pass

261

262

263 class TriangleError(_ValueError): # in .resections, .vector2d

264 '''Error raised for triangle, inter- or resection issues.

265 '''

266 pass

267

268

269 class SciPyError(PointsError):

270 '''Error raised for C{SciPy} issues.

271 '''

272 pass

273

274

275 class SciPyWarning(PointsError):

276 '''Error thrown for C{SciPy} warnings.

277

278 To raise C{SciPy} warnings as L{SciPyWarning} exceptions, Python

279 C{warnings} must be filtered as U{warnings.filterwarnings('error')

280 <https://docs.Python.org/3/library/warnings.html#the-warnings-filter>}

281 I{prior to} C{import scipy} OR by setting env var U{PYTHONWARNINGS

282 <https://docs.Python.org/3/using/cmdline.html#envvar-PYTHONWARNINGS>}

283 OR by invoking C{python} with command line option U{-W<https://docs.

284 Python.org/3/using/cmdline.html#cmdoption-w>} set to C{-W error}.

285 '''

286 pass

287

288

289 class TRFError(_ValueError): # in .ellipsoidalBase, .trf, .units

290 '''Terrestrial Reference Frame (TRF), L{Epoch}, L{RefFrame}

291 or L{RefFrame} conversion issue.

292 '''

293 pass

294

295

296 class UnitError(_ValueError): # in .named, .units

297 '''Default exception for L{units} issues.

298 '''

299 pass

300

301

302 class VectorError(_ValueError): # in .nvectorBase, .vector3d, .vector3dBase

303 '''L{Vector3d}, C{Cartesian*} or C{*Nvector} issues.

304 '''

305 pass

306

307

308 def _an(noun):

309 '''(INTERNAL) Prepend an article to a noun based

310 on the pronounciation of the first letter.

311 '''

312 a = _an_ if noun[:1].lower() in 'aeinoux' else _a_

313 return _SPACE_(a, noun)

314

315

316 def _and(*words):

317 '''(INTERNAL) Join C{words} with C{", "} and C{" and "}.

318 '''

319 return _and_or(_and_, *words)

320

321

322 def _and_or(last, *words):

323 '''(INTERNAL) Join C{words} with C{", "} and C{B{last}}.

324 '''

325 t, w = NN, list(words)

326 if w:

327 t = w.pop()

328 if w:

329 w = _COMMASPACE_.join(w)

330 t = _SPACE_(w, last, t)

331 return t

332

333

334 def crosserrors(raiser=None):

335 '''Report or ignore vectorial cross product errors.

336

337 @kwarg raiser: Use C{True} to throw or C{False} to ignore

338 L{CrossError} exceptions. Use C{None} to

339 leave the setting unchanged.

340

341 @return: Previous setting (C{bool}).

342

343 @see: Property C{Vector3d[Base].crosserrors}.

344 '''

345 B = _MODS.vector3dBase.Vector3dBase

346 t = B._crosserrors # XXX class attr!

347 if raiser in (True, False):

348 B._crosserrors = raiser

349 return t

350

351

352 def _error_init(Error, inst, args, fmt_name_value='%s (%r)', txt=NN,

353 cause=None, **kwds): # by .lazily

354 '''(INTERNAL) Format an error text and initialize an C{Error} instance.

355

356 @arg Error: The error super-class (C{Exception}).

357 @arg inst: Sub-class instance to be __init__-ed (C{_Exception}).

358 @arg args: Either just a value or several name, value, ...

359 positional arguments (C{str}, any C{type}), in

360 particular for name conflicts with keyword

361 arguments of C{error_init} or which can't be

362 given as C{name=value} keyword arguments.

363 @kwarg fmt_name_value: Format for (name, value) (C{str}).

364 @kwarg txt: Optional explanation of the error (C{str}).

365 @kwarg cause: Optional, caught error (L{Exception}), for

366 exception chaining (supported in Python 3+).

367 @kwarg kwds: Additional C{B{name}=value} pairs, if any.

368 '''

369 def _fmtuple(pairs):

370 return tuple(fmt_name_value % t for t in pairs)

371

372 t, n = (), len(args)

373 if n > 2:

374 s = _MODS.basics.isodd(n)

375 t = _fmtuple(zip(args[0::2], args[1::2]))

376 if s: # XXX _xzip(..., strict=s)

377 t += args[-1:]

378 elif n == 2:

379 t = (fmt_name_value % args),

380 elif n: # == 1

381 t = str(args[0]),

382

383 if kwds:

384 t += _fmtuple(itemsorted(kwds))

385 t = _or(*t) if t else _SPACE_(_name_value_, MISSING)

386

387 if txt is not None:

388 x = str(txt) or (str(cause) if cause else _invalid_)

389 C = _COMMASPACE_ if _COLON_ in t else _COLONSPACE_

390 t = C(t, x)

391# else: # LenError, _xzip, .dms, .heights, .vector2d

392# x = NN # XXX or t?

393 Error.__init__(inst, t)

394# inst.__x_txt__ = x # hold explanation

395 _error_cause(inst, cause=cause if _exception_chaining else None)

396 _error_under(inst)

397

398

399 def _error_under(inst):

400 '''(INTERNAL) Remove leading underscore from instance' class name.

401 '''

402 n = inst.__class__.__name__

403 if n.startswith(_UNDER_):

404 inst.__class__.__name__ = n.lstrip(_UNDER_)

405 return inst

406

407

408 def exception_chaining(error=None):

409 '''Get an error's I{cause} or the exception chaining setting.

410

411 @kwarg error: An error instance (C{Exception}) or C{None}.

412

413 @return: If C{B{error} is None}, return C{True} if exception

414 chaining is enabled for PyGeodesy errors, C{False}

415 if turned off and C{None} if not available. If

416 B{C{error}} is not C{None}, return it's error

417 I{cause} or C{None}.

418

419 @note: To enable exception chaining for C{pygeodesy} errors,

420 set env var C{PYGEODESY_EXCEPTION_CHAINING} to any

421 non-empty value prior to C{import pygeodesy}.

422 '''

423 return _exception_chaining if error is None else \

424 getattr(error, '__cause__', None)

425

426

427 def _incompatible(this):

428 '''(INTERNAL) Format an C{"incompatible with ..."} text.

429 '''

430 return _SPACE_(_incompatible_, _with_, this)

431

432

433 def _InvalidError(Error=_ValueError, **txt_name_values_cause): # txt=_invalid_, name=value [, ...]

434 '''(INTERNAL) Create an C{Error} instance.

435

436 @kwarg Error: The error class or sub-class (C{Exception}).

437 @kwarg txt_name_values: One or more C{B{name}=value} pairs

438 and optionally, keyword argument C{B{txt}=str}

439 to override the default C{B{txt}='invalid'} and

440 C{B{cause}=None} for exception chaining.

441

442 @return: An B{C{Error}} instance.

443 '''

444 return _XError(Error, **txt_name_values_cause)

445

446

447 def isError(obj):

448 '''Check a (caught) exception.

449

450 @arg obj: The exception C({Exception}).

451

452 @return: C{True} if B{C{obj}} is a C{pygeodesy} error,

453 C{False} if B{C{obj}} is a standard Python error

454 of C{None} if neither.

455 '''

456 return True if isinstance(obj, _XErrors) else (

457 False if isinstance(obj, Exception) else None)

458

459

460 def _IsnotError(*nouns, **name_value_Error_cause): # name=value [, Error=TypeError, cause=None]

461 '''Create a C{TypeError} for an invalid C{name=value} type.

462

463 @arg nouns: One or more expected class or type names, usually nouns (C{str}).

464 @kwarg name_value_Error_cause: One C{B{name}=value} pair and optionally,

465 keyword argument C{B{Error}=TypeError} to override the default

466 and C{B{cause}=None} for exception chaining.

467

468 @return: A C{TypeError} or an B{C{Error}} instance.

469 '''

470 x, Error = _xkwds_pop_(name_value_Error_cause, cause=None, Error=TypeError)

471 n, v = _xkwds_popitem(name_value_Error_cause) if name_value_Error_cause \

472 else (_name_value_, MISSING) # XXX else tuple(...)

473 n = _MODS.streprs.Fmt.PARENSPACED(n, repr(v))

474 t = _not_(_an(_or(*nouns)) if nouns else _specified_)

475 return _XError(Error, n, txt=t, cause=x)

476

477

478 def itemsorted(adict, *args, **asorted_reverse):

479 '''Return the items of C{B{adict}} sorted I{alphabetically, case-insensitively}

480 and in I{ascending} order.

481

482 @arg args: Optional argument(s) for method C{B{adict}.items(B*{args})}.

483 @kwarg asorted_reverse: Use keyword argument C{B{asorted}=False} for

484 I{case-sensitive} sorting and C{B{reverse}=True} for

485 results in C{descending} order.

486 '''

487 def _un(item):

488 return item[0].lower()

489

490 # see .rhumb.Rhumb and ._RhumbLine

491 a, r = _xkwds_get_(asorted_reverse, asorted=True, reverse=False) \

492 if asorted_reverse else (True, False)

493 items = adict.items(*args) if args else adict.items()

494 return sorted(items, reverse=r, key=_un if a else None)

495

496

497 def limiterrors(raiser=None):

498 '''Get/set the throwing of L{LimitError}s.

499

500 @kwarg raiser: Choose C{True} to raise or C{False} to

501 ignore L{LimitError} exceptions. Use

502 C{None} to leave the setting unchanged.

503

504 @return: Previous setting (C{bool}).

505 '''

506 global _limiterrors

507 t = _limiterrors

508 if raiser in (True, False):

509 _limiterrors = raiser

510 return t

511

512

513 def _or(*words):

514 '''(INTERNAL) Join C{words} with C{", "} and C{" or "}.

515 '''

516 return _and_or(_or_, *words)

517

518

519 def _parseX(parser, *args, **name_values_Error): # name=value[, ..., Error=ParseError]

520 '''(INTERNAL) Invoke a parser and handle exceptions.

521

522 @arg parser: The parser (C{callable}).

523 @arg args: Any B{C{parser}} arguments (any C{type}s).

524 @kwarg name_values_Error: Any C{B{name}=value} pairs and

525 optionally, C{B{Error}=ParseError} keyword

526 argument to override the default.

527

528 @return: Parser result.

529

530 @raise ParseError: Or the specified C{B{Error}}.

531 '''

532 try:

533 return parser(*args)

534 except Exception as x:

535 E = _xkwds_pop(name_values_Error, Error=type(x) if isError(x) else

536 ParseError)

537 raise _XError(E, **_xkwds(name_values_Error, cause=x))

538

539

540 def rangerrors(raiser=None):

541 '''Get/set the throwing of L{RangeError}s.

542

543 @kwarg raiser: Choose C{True} to raise or C{False} to ignore

544 L{RangeError} exceptions. Use C{None} to leave

545 the setting unchanged.

546

547 @return: Previous setting (C{bool}).

548 '''

549 global _rangerrors

550 t = _rangerrors

551 if raiser in (True, False):

552 _rangerrors = raiser

553 return t

554

555

556 def _SciPyIssue(x, *extras): # PYCHOK no cover

557 if isinstance(x, (RuntimeWarning, UserWarning)):

558 Error = SciPyWarning

559 else:

560 Error = SciPyError # PYCHOK not really

561 t = _SPACE_(str(x).strip(), *extras)

562 return Error(t, cause=x)

563

564

565 def _xdatum(datum1, datum2, Error=None):

566 '''(INTERNAL) Check for datum, ellipsoid or rhumb mis-match.

567 '''

568 if Error:

569 E1, E2 = datum1.ellipsoid, datum2.ellipsoid

570 if E1 != E2:

571 raise Error(E2.named2, txt=_incompatible(E1.named2))

572 elif datum1 != datum2:

573 t = _SPACE_(_datum_, repr(datum1.name), _not_, repr(datum2.name))

574 raise _AssertionError(t)

575

576

577 def _xellipsoidal(**name_value):

578 '''(INTERNAL) Check an I{ellipsoidal} item.

579

580 @return: The B{C{value}} if ellipsoidal.

581

582 @raise TypeError: Not ellipsoidal B{C{value}}.

583 '''

584 try:

585 for n, v in name_value.items():

586 if v.isEllipsoidal:

587 return v

588 break

589 else:

590 n = v = MISSING

591 except AttributeError:

592 pass

593 raise _TypeError(n, v, txt=_not_(_ellipsoidal_))

594

595

596 def _XError(Error, *args, **kwds):

597 '''(INTERNAL) Format an C{Error} or C{_Error}.

598 '''

599 try: # C{_Error} style

600 return Error(*args, **kwds)

601 except TypeError: # no keyword arguments

602 pass

603 e = _ValueError(*args, **kwds)

604 E = Error(str(e))

605 if _exception_chaining:

606 _error_cause(E, cause=e.__cause__) # PYCHOK OK

607 return E

608

609

610_XErrors = _TypeError, _ValueError

611# map certain C{Exception} classes to the C{_Error}

612_X2Error = {AssertionError: _AssertionError,

613 AttributeError: _AttributeError,

614 ImportError: _ImportError,

615 IndexError: _IndexError,

616 KeyError: _KeyError,

617 NameError: _NameError,

618 NotImplementedError: _NotImplementedError,

619 OverflowError: _OverflowError,

620 TypeError: _TypeError,

621 ValueError: _ValueError,

622 ZeroDivisionError: _ZeroDivisionError}

623

624

625 def _xError(x, *args, **kwds):

626 '''(INTERNAL) Embellish a (caught) exception.

627

628 @arg x: The exception (usually, C{_Error}).

629 @arg args: Embelishments (C{any}).

630 @kwarg kwds: Embelishments (C{any}).

631 '''

632 return _XError(type(x), *args, **_xkwds(kwds, cause=x))

633

634

635 def _xError2(x): # in .fsums

636 '''(INTERNAL) Map an exception to 2-tuple (C{_Error} class, error C{txt}).

637

638 @arg x: The exception instance (usually, C{Exception}).

639 '''

640 X = type(x)

641 E = _X2Error.get(X, X)

642 if E is X and not isError(x):

643 E = _NotImplementedError

644 t = repr(x)

645 else:

646 t = str(x)

647 return E, t

648

649

650 try:

651 _ = {}.__or__ # {} | {} # Python 3.9+

652

653 def _xkwds(kwds, **dflts):

654 '''(INTERNAL) Override C{dflts} with specified C{kwds}.

655 '''

656 return (dflts | kwds) if kwds else dflts

657

658 except AttributeError:

659 from copy import copy as _copy

660

661 def _xkwds(kwds, **dflts): # PYCHOK expected

662 '''(INTERNAL) Override C{dflts} with specified C{kwds}.

663 '''

664 d = dflts

665 if kwds:

666 d = _copy(d)

667 d.update(kwds)

668 return d

669

670

671 def _xkwds_Error(where, kwds, name_txt, txt=_default_):

672 # Helper for _xkwds_get, _xkwds_pop and _xkwds_popitem below

673 f = _COMMASPACE_.join(_pairs(kwds) + _pairs(name_txt))

674 f = _MODS.streprs.Fmt.PAREN(where.__name__, f)

675 t = _multiple_ if name_txt else _no_

676 t = _SPACE_(t, _EQUAL_(_name_, txt), _kwargs_)

677 return _AssertionError(f, txt=t)

678

679

680 def _xkwds_get(kwds, **name_default):

681 '''(INTERNAL) Get a C{kwds} value by C{name}, or the C{default}.

682 '''

683 if len(name_default) == 1:

684 for n, d in name_default.items():

685 return kwds.get(n, d)

686 raise _xkwds_Error(_xkwds_get, kwds, name_default)

687

688

689 def _xkwds_get_(kwds, **names_defaults):

690 '''(INTERNAL) Yield each C{kwds} value or its C{default}

691 in I{case-insensitive, alphabetical} order.

692 '''

693 for n, d in itemsorted(names_defaults):

694 yield kwds.get(n, d)

695

696

697 def _xkwds_not(*args, **kwds):

698 '''(INTERNAL) Return C{kwds} with a value not in C{args}.

699 '''

700 return dict((n, v) for n, v in kwds.items() if v not in args)

701

702

703 def _xkwds_pop(kwds, **name_default):

704 '''(INTERNAL) Pop a C{kwds} value by C{name}, or the C{default}.

705 '''

706 if len(name_default) == 1:

707 for n, d in name_default.items():

708 return kwds.pop(n, d)

709 raise _xkwds_Error(_xkwds_pop, kwds, name_default)

710

711

712 def _xkwds_pop_(kwds, **names_defaults):

713 '''(INTERNAL) Pop and yield each C{kwds} value or its C{default}

714 in I{case-insensitive, alphabetical} order.

715 '''

716 for n, d in itemsorted(names_defaults):

717 yield kwds.pop(n, d)

718

719

720 def _xkwds_popitem(name_value):

721 '''(INTERNAL) Return exactly one C{(name, value)} item.

722 '''

723 if len(name_value) == 1: # XXX TypeError

724 return name_value.popitem() # XXX AttributeError

725 raise _xkwds_Error(_xkwds_popitem, (), name_value, txt=_value_)

726

727

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

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

730 '''

731 s = _xkwds_get(strict, strict=True)

732 if s:

733 _zip = _MODS.basics._zip

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

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

736 raise _NotImplementedError(t, txt=None)

737 return _zip(*args)

738 return zip(*args)

739

740# **) MIT License

741#

742# Copyright (C) 2016-2023 -- mrJean1 at Gmail -- All Rights Reserved.

743#

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

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

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

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

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

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

750#

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

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

753#

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

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

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

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

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

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

760# OTHER DEALINGS IN THE SOFTWARE.