Coverage for pygeodesy/streprs.py: 96%

272 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-03-03 11:31 -0500

1 

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

3 

4u'''Floating point and other formatting utilities. 

5''' 

6 

7from pygeodesy.basics import isint, islistuple, isscalar, isstr, itemsorted, \ 

8 _zip, _0_0 

9# from pygeodesy.constants import _0_0 

10from pygeodesy.errors import _AttributeError, _IsnotError, _or, _TypeError, \ 

11 _ValueError, _xkwds_get, _xkwds_pop2 

12from pygeodesy.interns import NN, _0_, _0to9_, MISSING, _BAR_, _COMMASPACE_, \ 

13 _DOT_, _dunder_nameof, _E_, _ELLIPSIS_, _EQUAL_, \ 

14 _H_, _LR_PAIRS, _N_, _name_, _not_, _not_scalar_, \ 

15 _PERCENT_, _SPACE_, _STAR_, _UNDER_ 

16from pygeodesy.interns import _convergence_, _distant_, _e_, _eps_, _exceeds_, \ 

17 _EQUALSPACED_, _f_, _F_, _g_, _limit_, _no_, \ 

18 _tolerance_ # PYCHOK used! 

19from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, _getenv 

20 

21from math import fabs, log10 as _log10 

22 

23__all__ = _ALL_LAZY.streprs 

24__version__ = '24.02.20' 

25 

26_EN_PREC = 6 # max MGRS/OSGR precision, 1 micrometer 

27_EN_WIDE = 5 # number of MGRS/OSGR units, log10(_100km) 

28_OKd_ = '._-' # acceptable name characters 

29_PAREN_g = '(%g)' # PYCHOK used! 

30_threshold_ = 'threshold' # PYCHOK used! 

31 

32 

33class _Fmt(str): # in .streprs 

34 '''(INTERNAL) Callable formatting. 

35 ''' 

36 name = NN 

37 

38 def __call__(self, *name_value_, **name_value): 

39 '''Format a C{name=value} pair or C{name, value} pair 

40 or just a single C{value}. 

41 ''' 

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

43 break 

44 else: 

45 if len(name_value_) > 1: 

46 n, v = name_value_[:2] 

47 elif name_value_: 

48 n, v = NN, name_value_[0] 

49 else: 

50 n, v = NN, MISSING 

51 t = str.__mod__(self, v) 

52 return NN(n, t) if n else t 

53 

54# def __mod__(self, arg, **unused): 

55# '''Regular C{%} operator. 

56# ''' 

57# return str.__mod__(self, arg) 

58 

59 

60class Fstr(str): 

61 '''(INTERNAL) C{float} format. 

62 ''' 

63 name = NN 

64 

65 def __call__(self, flt, prec=None, ints=False): 

66 '''Format the B{C{flt}} like function L{fstr}. 

67 ''' 

68 # see also function C{fstr} if isscalar case below 

69 t = str.__mod__(_pct(self), flt) if prec is None else next( 

70 _streprs(prec, (flt,), self, ints, True, None)) 

71 return t 

72 

73 def __mod__(self, arg, **unused): 

74 '''Regular C{%} operator. 

75 

76 @arg arg: A C{scalar} value to be formatted (either 

77 the C{scalar}, or a 1-tuple C{(scalar,)}, 

78 or 2-tuple C{(prec, scalar)}. 

79 

80 @raise TypeError: Non-scalar B{C{arg}} value. 

81 

82 @raise ValueError: Invalid B{C{arg}}. 

83 ''' 

84 def _error(arg): 

85 n = _DOT_(Fstr.__name__, self.name or self) 

86 return _SPACE_(n, _PERCENT_, repr(arg)) 

87 

88 prec = 6 # default std %f and %F 

89 if islistuple(arg): 

90 n = len(arg) 

91 if n == 1: 

92 arg = arg[0] 

93 elif n == 2: 

94 prec, arg = arg 

95 else: 

96 raise _ValueError(_error(arg)) 

97 

98 if not isscalar(arg): 

99 raise _TypeError(_error(arg)) 

100 return self(arg, prec=prec) 

101 

102 

103class _Sub(str): 

104 '''(INTERNAL) Class list formatter. 

105 ''' 

106 # see .ellipsoidalNvector.LatLon.deltaTo 

107 def __call__(self, *Classes): 

108 t = _or(*(C.__name__ for C in Classes)) 

109 return str.__mod__(self, t or MISSING) 

110 

111 

112class Fmt(object): 

113 '''Formatting options. 

114 ''' 

115 ANGLE = _Fmt('<%s>') 

116 COLON = _Fmt(':%s') 

117# COLONSPACE = _Fmt(': %s') # == _COLONSPACE_(n, v) 

118# COMMASPACE = _Fmt(', %s') # == _COMMASPACE_(n, v) 

119 convergence = _Fmt(_convergence_(_PAREN_g)) 

120 CURLY = _Fmt('{%s}') # BRACES 

121 distant = _Fmt(_distant_('(%.3g)')) 

122 DOT = _Fmt('.%s') # == NN(_DOT_, n) 

123 e = Fstr(_e_) 

124 E = Fstr(_E_) 

125 EQUAL = _Fmt(_EQUAL_(NN, '%s')) 

126 EQUALg = _Fmt(_EQUAL_(NN, '%g')) 

127 EQUALSPACED = _Fmt(_EQUALSPACED_(NN, '%s')) 

128 exceeds_eps = _Fmt(_exceeds_(_eps_, _PAREN_g)) 

129 exceeds_limit = _Fmt(_exceeds_(_limit_, _PAREN_g)) 

130 f = Fstr(_f_) 

131 form = _getenv('PYGEODESY_FMT_FORM', NN) 

132 F = Fstr(_F_) 

133 g = Fstr(_g_) 

134 G = Fstr('G') 

135 h = Fstr('%+.*f') # height, .streprs.hstr 

136 limit = _Fmt(' %s limit') # .units 

137 LOPEN = _Fmt('(%s]') # left-open range (L, R] 

138 PAREN = _Fmt('(%s)') 

139 PAREN_g = _Fmt(_PAREN_g) 

140 PARENSPACED = _Fmt(' (%s)') 

141 QUOTE2 = _Fmt('"%s"') 

142 ROPEN = _Fmt('[%s)') # right-open range [L, R) 

143# SPACE = _Fmt(' %s') # == _SPACE_(n, v) 

144 SQUARE = _Fmt('[%s]') # BRACKETS 

145 sub_class = _Sub('%s (sub-)class') 

146 TAG = ANGLE 

147 TAGEND = _Fmt('</%s>') 

148 tolerance = _Fmt(_tolerance_(_PAREN_g)) 

149 zone = _Fmt('%02d') # .epsg, .mgrs, .utmupsBase 

150 

151 def __init__(self): 

152 for n, a in self.__class__.__dict__.items(): 

153 if isinstance(a, (Fstr, _Fmt)): 

154 setattr(a, _name_, n) 

155 

156 def __call__(self, obj, prec=9): 

157 '''Return C{str(B{obj})} or C{repr(B{obj})}. 

158 ''' 

159 return str(obj) if isint(obj) else next( 

160 _streprs(prec, (obj,), Fmt.g, False, False, repr)) 

161 

162 def INDEX(self, name, i=None): 

163 return name if i is None else self.SQUARE(name, i) 

164 

165 def no_convergence(self, _d, *tol, **thresh): 

166 t = Fmt.convergence(fabs(_d)) 

167 if tol: 

168 t = _COMMASPACE_(t, Fmt.tolerance(tol[0])) 

169 if thresh and _xkwds_get(thresh, thresh=False): 

170 t = t.replace(_tolerance_, _threshold_) 

171 return _no_(t) 

172 

173Fmt = Fmt() # PYCHOK singleton 

174Fmt.__name__ = Fmt.__class__.__name__ 

175 

176_DOTSTAR_ = Fmt.DOT(_STAR_) 

177# formats %G and %g drop all trailing zeros and the 

178# decimal point, making the float appear as an int 

179_Gg = (Fmt.G, Fmt.g) 

180_FfEeGg = (Fmt.F, Fmt.f, Fmt.E, Fmt.e) + _Gg # float formats 

181_Fspec_ = NN('[%[<flags>][<width>]', _DOTSTAR_, ']', _BAR_.join(_FfEeGg)) # in testStreprs 

182 

183 

184def anstr(name, OKd=_OKd_, sub=_UNDER_): 

185 '''Make a valid name of alphanumeric and OKd characters. 

186 

187 @arg name: The original name (C{str}). 

188 @kwarg OKd: Other acceptable characters (C{str}). 

189 @kwarg sub: Substitute for invalid charactes (C{str}). 

190 

191 @return: The modified name (C{str}). 

192 

193 @note: Leading and trailing whitespace characters are removed, 

194 intermediate whitespace characters are coalesced and 

195 substituted. 

196 ''' 

197 s = n = str(name).strip() 

198 for c in n: 

199 if not (c.isalnum() or c in OKd or c in sub): 

200 s = s.replace(c, _SPACE_) 

201 return sub.join(s.strip().split()) 

202 

203 

204def attrs(inst, *names, **Nones_True__pairs_kwds): # prec=6, fmt=Fmt.F, ints=False, Nones=True, sep=_EQUAL_ 

205 '''Get instance attributes as I{name=value} strings, with C{float}s 

206 formatted by function L{fstr}. 

207 

208 @arg inst: The instance (any C{type}). 

209 @arg names: The attribute names, all other positional (C{str}). 

210 @kwarg Nones_True__pairs_kwds: Keyword argument for function L{pairs}, except 

211 C{B{Nones}=True} to in-/exclude missing or C{None}-valued attributes. 

212 

213 @return: A C{tuple(B{sep}.join(t) for t in zip(B{names}, reprs(values, ...)))} 

214 of C{str}s. 

215 ''' 

216 def _items(inst, names, Nones): 

217 for n in names: 

218 v = getattr(inst, n, None) 

219 if Nones or v is not None: 

220 yield n, v 

221 

222 def _Nones_kwds(Nones=True, **kwds): 

223 return Nones, kwds 

224 

225 Nones, kwds = _Nones_kwds(**Nones_True__pairs_kwds) 

226 return pairs(_items(inst, names, Nones), **kwds) 

227 

228 

229def enstr2(easting, northing, prec, *extras, **wide_dot): 

230 '''Return an MGRS/OSGR easting, northing string representations. 

231 

232 @arg easting: Easting from false easting (C{meter}). 

233 @arg northing: Northing from from false northing (C{meter}). 

234 @arg prec: Precision, the number of I{decimal} digits (C{int}) or if 

235 negative, the number of I{units to drop}, like MGRS U{PRECISION 

236 <https://GeographicLib.SourceForge.io/C++/doc/GeoConvert.1.html#PRECISION>}. 

237 @arg extras: Optional leading items (C{str}s). 

238 @kwarg wide_dot: Optional keword argument C{B{wide}=%d} for the number of I{unit digits} 

239 (C{int}) and C{B{dot}=False} (C{bool}) to insert a decimal point. 

240 

241 @return: B{C{extras}} + 2-tuple C{(str(B{easting}), str(B{northing}))} or 

242 + 2-tuple C{("", "")} for C{B{prec} <= -B{wide}}. 

243 

244 @raise ValueError: Invalid B{C{easting}}, B{C{northing}} or B{C{prec}}. 

245 

246 @note: The B{C{easting}} and B{C{northing}} values are I{truncated, not rounded}. 

247 ''' 

248 t = extras 

249 try: # like .dms.compassPoint 

250 p = min(int(prec), _EN_PREC) 

251 w = p + _xkwds_get(wide_dot, wide=_EN_WIDE) 

252 if w > 0: 

253 f = 10**p # truncate 

254 d = (-p) if p > 0 and _xkwds_get(wide_dot, dot=False) else 0 

255 t += (_0wdot(w, int(easting * f), d), 

256 _0wdot(w, int(northing * f), d)) 

257 else: # prec <= -_EN_WIDE 

258 t += (NN, NN) 

259 except (TypeError, ValueError) as x: 

260 raise _ValueError(easting=easting, northing=northing, prec=prec, cause=x) 

261 return t 

262 

263if enstr2.__doc__: # PYCHOK expected 

264 enstr2.__doc__ %= (_EN_WIDE,) 

265 

266 

267def _enstr2m3(estr, nstr, wide=_EN_WIDE): # in .mgrs, .osgr 

268 '''(INTERNAL) Convert east- and northing C{str}s to meter and resolution. 

269 ''' 

270 def _s2m2(s, m): # e or n str to float meter 

271 if _DOT_ in s: 

272 m = 1 # meter 

273 else: 

274 s += _0_ * wide 

275 s = _DOT_(s[:wide], s[wide:wide+_EN_PREC]) 

276 return float(s), m 

277 

278 e, m = _s2m2(estr, 0) 

279 n, m = _s2m2(nstr, m) 

280 if not m: 

281 p = max(len(estr), len(nstr)) # 2 = Km, 5 = m, 7 = cm 

282 m = 10**max(-_EN_PREC, wide - p) # resolution, meter 

283 return e, n, m 

284 

285 

286def fstr(floats, prec=6, fmt=Fmt.F, ints=False, sep=_COMMASPACE_, strepr=None): 

287 '''Convert one or more floats to string, optionally stripped of trailing zero decimals. 

288 

289 @arg floats: Single or a list, sequence, tuple, etc. (C{scalar}s). 

290 @kwarg prec: The C{float} precision, number of decimal digits (0..9). 

291 Trailing zero decimals are stripped if B{C{prec}} is 

292 positive, but kept for negative B{C{prec}} values. In 

293 addition, trailing decimal zeros are stripped for U{alternate, 

294 form '#'<https://docs.Python.org/3/library/stdtypes.html 

295 #printf-style-string-formatting>}. 

296 @kwarg fmt: Optional C{float} format (C{letter}). 

297 @kwarg ints: Optionally, remove the decimal dot for C{int} values (C{bool}). 

298 @kwarg sep: Separator joining the B{C{floats}} (C{str}). 

299 @kwarg strepr: Optional callable to format non-C{floats} (typically 

300 C{repr}, C{str}) or C{None} to raise a TypeError. 

301 

302 @return: The C{sep.join(strs(floats, ...)} joined (C{str}) or single 

303 C{strs((floats,), ...)} (C{str}) if B{C{floats}} is C{scalar}. 

304 ''' 

305 if isscalar(floats): # see Fstr.__call__ above 

306 return next(_streprs(prec, (floats,), fmt, ints, True, strepr)) 

307 else: 

308 return sep.join(_streprs(prec, floats, fmt, ints, True, strepr)) 

309 

310 

311def _fstrENH2(inst, prec, m, fmt=Fmt.F): # in .css, .lcc, .utmupsBase 

312 # (INTERNAL) For C{Css.} and C{Lcc.} C{toRepr} and C{toStr} and C{UtmUpsBase._toStr}. 

313 t = inst.easting, inst.northing 

314 t = tuple(_streprs(prec, t, fmt, False, True, None)) 

315 T = _E_, _N_ 

316 if m is not None and fabs(inst.height): # fabs(self.height) > EPS 

317 t += hstr(inst.height, prec=-2, m=m), 

318 T += _H_, 

319 return t, T 

320 

321 

322def _fstrLL0(inst, prec, toRepr): # in .azimuthal, .css 

323 # (INTERNAL) For C{_AlbersBase.}, C{_AzimuthalBase.} and C{CassiniSoldner.} 

324 t = tuple(_streprs(prec, inst.latlon0, Fmt.F, False, True, None)) 

325 if toRepr: 

326 n = inst.name 

327 if n: 

328 t += Fmt.EQUAL(_name_, repr(n)), 

329 t = Fmt.PAREN(inst.classname, _COMMASPACE_.join(t)) 

330 return t 

331 

332 

333def fstrzs(efstr, ap1z=False): 

334 '''Strip trailing zero decimals from a C{float} string. 

335 

336 @arg efstr: Float with or without exponent (C{str}). 

337 @kwarg ap1z: Append the decimal point and one zero decimal 

338 if the B{C{efstr}} is all digits (C{bool}). 

339 

340 @return: Float (C{str}). 

341 ''' 

342 s = efstr.find(_DOT_) 

343 if s >= 0: 

344 e = efstr.rfind(Fmt.e) 

345 if e < 0: 

346 e = efstr.rfind(Fmt.E) 

347 if e < 0: 

348 e = len(efstr) 

349 s += 2 # keep 1st _DOT_ + _0_ 

350 if s < e and efstr[e-1] == _0_: 

351 efstr = NN(efstr[:s], efstr[s:e].rstrip(_0_), efstr[e:]) 

352 

353 elif ap1z: 

354 # %.G and %.g formats may drop the decimal 

355 # point and all trailing zeros, ... 

356 if efstr.isdigit(): 

357 efstr += _DOT_ + _0_ # ... append or ... 

358 else: # ... insert one dot and zero 

359 e = efstr.rfind(Fmt.e) 

360 if e < 0: 

361 e = efstr.rfind(Fmt.E) 

362 if e > 0: 

363 efstr = NN(efstr[:e], _DOT_, _0_, efstr[e:]) 

364 

365 return efstr 

366 

367 

368def hstr(height, prec=2, fmt=Fmt.h, ints=False, m=NN): 

369 '''Return a string for the height value. 

370 

371 @arg height: Height value (C{float}). 

372 @kwarg prec: The C{float} precision, number of decimal digits (0..9). 

373 Trailing zero decimals are stripped if B{C{prec}} is 

374 positive, but kept for negative B{C{prec}} values. 

375 @kwarg fmt: Optional C{float} format (C{letter}). 

376 @kwarg ints: Optionally, remove the decimal dot for C{int} values (C{bool}). 

377 @kwarg m: Optional unit of the height (C{str}). 

378 ''' 

379 h = next(_streprs(prec, (height,), fmt, ints, True, None)) 

380 return NN(h, str(m)) if m else h 

381 

382 

383def instr(inst, *args, **kwds): 

384 '''Return the string representation of an instantiation. 

385 

386 @arg inst: The instance (any C{type}). 

387 @arg args: Optional positional arguments. 

388 @kwarg kwds: Optional keyword arguments. 

389 

390 @return: Representation (C{str}). 

391 ''' 

392 return unstr(_MODS.named.classname(inst), *args, **kwds) 

393 

394 

395def lrstrip(txt, lrpairs=_LR_PAIRS): 

396 '''Left- I{and} right-strip parentheses, brackets, etc. from a string. 

397 

398 @arg txt: String to be stripped (C{str}). 

399 @kwarg lrpairs: Parentheses, etc. to remove (C{dict} of one or several 

400 C{(Left, Right)} pairs). 

401 

402 @return: Stripped B{C{txt}} (C{str}). 

403 ''' 

404 _e, _s, _n = str.endswith, str.startswith, len 

405 while _n(txt) > 2: 

406 for L, R in lrpairs.items(): 

407 if _e(txt, R) and _s(txt, L): 

408 txt = txt[_n(L):-_n(R)] 

409 break # restart 

410 else: 

411 return txt 

412 

413 

414def pairs(items, prec=6, fmt=Fmt.F, ints=False, sep=_EQUAL_): 

415 '''Convert items to I{name=value} strings, with C{float}s handled like L{fstr}. 

416 

417 @arg items: Name-value pairs (C{dict} or 2-{tuple}s of any C{type}s). 

418 @kwarg prec: The C{float} precision, number of decimal digits (0..9). 

419 Trailing zero decimals are stripped if B{C{prec}} is 

420 positive, but kept for negative B{C{prec}} values. 

421 @kwarg fmt: Optional C{float} format (C{letter}). 

422 @kwarg ints: Optionally, remove the decimal dot for C{int} values (C{bool}). 

423 @kwarg sep: Separator joining I{names} and I{values} (C{str}). 

424 

425 @return: A C{tuple(B{sep}.join(t) for t in B{items}))} of C{str}s. 

426 ''' 

427 try: 

428 if isinstance(items, dict): 

429 items = itemsorted(items) 

430 elif not islistuple(items): 

431 items = tuple(items) 

432 # can't unzip empty items tuple, list, etc. 

433 n, v = _zip(*items) if items else ((), ()) # strict=True 

434 except (TypeError, ValueError): 

435 raise _IsnotError(dict.__name__, '2-tuples', items=items) 

436 v = _streprs(prec, v, fmt, ints, False, repr) 

437 return tuple(sep.join(t) for t in _zip(map(str, n), v)) # strict=True 

438 

439 

440def _pct(fmt): 

441 '''(INTERNAL) Prefix C{%} if needed. 

442 ''' 

443 return fmt if _PERCENT_ in fmt else NN(_PERCENT_, fmt) 

444 

445 

446def reprs(objs, prec=6, fmt=Fmt.F, ints=False): 

447 '''Convert objects to C{repr} strings, with C{float}s handled like L{fstr}. 

448 

449 @arg objs: List, sequence, tuple, etc. (any C{type}s). 

450 @kwarg prec: The C{float} precision, number of decimal digits (0..9). 

451 Trailing zero decimals are stripped if B{C{prec}} is 

452 positive, but kept for negative B{C{prec}} values. 

453 @kwarg fmt: Optional C{float} format (C{letter}). 

454 @kwarg ints: Optionally, remove the decimal dot for C{int} values (C{bool}). 

455 

456 @return: A C{tuple(map(fstr|repr, objs))} of C{str}s. 

457 ''' 

458 return tuple(_streprs(prec, objs, fmt, ints, False, repr)) if objs else () 

459 

460 

461def _resolution10(resolution, Error=ValueError): # in .mgrs, .osgr 

462 '''(INTERNAL) Validate C{resolution} in C{meter}. 

463 ''' 

464 try: 

465 r = int(_log10(resolution)) 

466 if _EN_WIDE < r or r < -_EN_PREC: 

467 raise ValueError 

468 except (ValueError, TypeError): 

469 raise Error(resolution=resolution) 

470 return _MODS.units.Meter(resolution=10**r) 

471 

472 

473def _streprs(prec, objs, fmt, ints, force, strepr): 

474 '''(INTERNAL) Helper for C{fstr}, C{pairs}, C{reprs} and C{strs} 

475 ''' 

476 # <https://docs.Python.org/3/library/stdtypes.html#printf-style-string-formatting> 

477 if fmt in _FfEeGg: 

478 fGg = fmt in _Gg 

479 fmt = NN(_PERCENT_, _DOT_, abs(prec), fmt) 

480 

481 elif fmt.startswith(_PERCENT_): 

482 fGg = False 

483 try: # to make sure fmt is valid 

484 f = fmt.replace(_DOTSTAR_, Fmt.DOT(abs(prec))) 

485 _ = f % (_0_0,) 

486 except (TypeError, ValueError): 

487 raise _ValueError(fmt=fmt, txt=_not_(repr(_DOTSTAR_))) 

488 fmt = f 

489 

490 else: 

491 raise _ValueError(fmt=fmt, txt=_not_(repr(_Fspec_))) 

492 

493 for i, o in enumerate(objs): 

494 if force or isinstance(o, float): 

495 t = fmt % (float(o),) 

496 if ints and t.rstrip(_0to9_ if isint(o, both=True) else 

497 _0_).endswith(_DOT_): 

498 t = t.split(_DOT_)[0] 

499 elif prec > 1: 

500 t = fstrzs(t, ap1z=fGg) 

501 elif strepr: 

502 t = strepr(o) 

503 else: 

504 t = Fmt.PARENSPACED(Fmt.SQUARE(objs=i), o) 

505 raise TypeError(_SPACE_(t, _not_scalar_)) 

506 yield t 

507 

508 

509def strs(objs, prec=6, fmt=Fmt.F, ints=False): 

510 '''Convert objects to C{str} strings, with C{float}s handled like L{fstr}. 

511 

512 @arg objs: List, sequence, tuple, etc. (any C{type}s). 

513 @kwarg prec: The C{float} precision, number of decimal digits (0..9). 

514 Trailing zero decimals are stripped if B{C{prec}} is 

515 positive, but kept for negative B{C{prec}} values. 

516 @kwarg fmt: Optional C{float} format (C{letter}). 

517 @kwarg ints: Optionally, remove the decimal dot for C{int} values (C{bool}). 

518 

519 @return: A C{tuple(map(fstr|str, objs))} of C{str}s. 

520 ''' 

521 return tuple(_streprs(prec, objs, fmt, ints, False, str)) if objs else () 

522 

523 

524def unstr(where, *args, **kwds): 

525 '''Return the string representation of an invokation. 

526 

527 @arg where: Class, function, method (C{type}) or name (C{str}). 

528 @arg args: Optional positional arguments. 

529 @kwarg kwds: Optional keyword arguments, except 

530 C{B{_ELLIPSIS}=False}. 

531 

532 @return: Representation (C{str}). 

533 ''' 

534 t = reprs(args, fmt=Fmt.g) if args else () 

535 e, kwds = _xkwds_pop2(kwds, _ELLIPSIS=False) 

536 if e: 

537 t += _ELLIPSIS_, 

538 if kwds: 

539 t += pairs(itemsorted(kwds), fmt=Fmt.g) 

540 n = where if isstr(where) else _dunder_nameof(where) 

541 return Fmt.PAREN(n, _COMMASPACE_.join(t)) 

542 

543 

544def _0wd(*w_i): # in .osgr, .wgrs 

545 '''(INTERNAL) Int formatter'. 

546 ''' 

547 return '%0*d' % w_i 

548 

549 

550def _0wdot(w, f, dot=0): 

551 '''(INTERNAL) Int and Float formatter'. 

552 ''' 

553 s = _0wd(w, int(f)) 

554 if dot: 

555 s = _DOT_(s[:dot], s[dot:]) 

556 return s 

557 

558 

559def _0wpF(*w_p_f): # in .dms, .osgr 

560 '''(INTERNAL) Float deg, min, sec formatter'. 

561 ''' 

562 return '%0*.*f' % w_p_f # XXX was F 

563 

564 

565def _xattrs(insto, other, *attrs): # see .errors._xattr 

566 '''(INTERNAL) Copy attribute values from B{C{other}} to B{C{insto}}. 

567 

568 @arg insto: Object to copy attribute values to (any C{type}). 

569 @arg other: Object to copy attribute values from (any C{type}). 

570 @arg attrs: One or more attribute names (C{str}s). 

571 

572 @return: Object B{C{insto}}, updated. 

573 

574 @raise AttributeError: An B{C{attrs}} doesn't exist 

575 or is not settable. 

576 ''' 

577 def _getattr(o, a): 

578 if hasattr(o, a): 

579 return getattr(o, a) 

580 try: 

581 n = o._DOT_(a) 

582 except AttributeError: 

583 n = Fmt.DOT(a) 

584 raise _AttributeError(o, name=n) 

585 

586 for a in attrs: 

587 s = _getattr(other, a) 

588 g = _getattr(insto, a) 

589 if (g is None and s is not None) or g != s: 

590 setattr(insto, a, s) # not settable? 

591 return insto 

592 

593 

594def _xzipairs(names, values, sep=_COMMASPACE_, fmt=NN, pair_fmt=Fmt.COLON): 

595 '''(INTERNAL) Zip C{names} and C{values} into a C{str}, joined and bracketed. 

596 ''' 

597 try: 

598 t = sep.join(pair_fmt(*t) for t in _zip(names, values)) # strict=True 

599 except Exception as x: 

600 raise _ValueError(names=names, values=values, cause=x) 

601 return (fmt % (t,)) if fmt else t # enc 

602 

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.