Coverage for pygeodesy/streprs.py: 96%

275 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2024-05-15 16:36 -0400

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 _or, _AttributeError, _IsnotError, _TypeError, \ 

11 _ValueError, _xkwds_get, _xkwds_item2, _xkwds_pop2 

12# from pygeodesy.internals import _dunder_nameof # from .lazily 

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

14 _DOT_, _E_, _ELLIPSIS_, _EQUAL_, _H_, _LR_PAIRS, \ 

15 _N_, _name_, _not_, _not_scalar_, _PERCENT_, \ 

16 _SPACE_, _STAR_, _UNDER_ 

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

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

19 _tolerance_ # PYCHOK used! 

20from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS, _dunder_nameof 

21 

22from math import fabs, log10 as _log10 

23 

24__all__ = _ALL_LAZY.streprs 

25__version__ = '24.05.13' 

26 

27_at_ = 'at' # PYCHOK used! 

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

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

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

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

32_RESIDUAL_ = 'RESIDUAL' # PYCHOK used! 

33_threshold_ = 'threshold' # PYCHOK used! 

34 

35 

36class _Fmt(str): 

37 '''(INTERNAL) Callable formatting. 

38 ''' 

39 name = NN 

40 

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

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

43 just a single C{value}. 

44 ''' 

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

46 break 

47 else: 

48 n, v = name_value_[:2] if len(name_value_) > 1 else \ 

49 (NN, (name_value_ or MISSING)) 

50 t = str.__mod__(self, v) 

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

52 

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

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

55# ''' 

56# return str.__mod__(self, arg) 

57 

58 

59class Fstr(str): 

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

61 ''' 

62 name = NN 

63 

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

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

66 ''' 

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

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

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

70 return t 

71 

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

73 '''Regular C{%} operator. 

74 

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

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

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

78 

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

80 

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

82 ''' 

83 def _error(arg): 

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

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

86 

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

88 if islistuple(arg): 

89 n = len(arg) 

90 if n == 1: 

91 arg = arg[0] 

92 elif n == 2: 

93 prec, arg = arg 

94 else: 

95 raise _ValueError(_error(arg)) 

96 

97 if not isscalar(arg): 

98 raise _TypeError(_error(arg)) 

99 return self(arg, prec=prec) # Fstr.__call__(self, arg, prec=prec) 

100 

101 

102class _Sub(str): 

103 '''(INTERNAL) Class list formatter. 

104 ''' 

105 # see .ellipsoidalNvector.LatLon.deltaTo 

106 def __call__(self, *Classes): 

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

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

109 

110 

111class Fmt(object): 

112 '''Formatting options. 

113 ''' 

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

115 COLON = _Fmt(':%s') 

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

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

118 convergence = _Fmt(_convergence_(_PAREN_g)) 

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

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

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

122 e = Fstr(_e_) 

123 E = Fstr(_E_) 

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

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

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

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

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

129 exceeds_R = _Fmt(_exceeds_(_RESIDUAL_, _PAREN_g)) 

130 f = Fstr(_f_) 

131 F = Fstr(_F_) 

132 g = Fstr(_g_) 

133 G = Fstr('G') 

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

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

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

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

138 PAREN_g = _Fmt(_PAREN_g) 

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

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

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

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

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

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

145 TAG = ANGLE 

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

147 tolerance = _Fmt(_tolerance_(_PAREN_g)) 

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

149 

150 def __init__(self): 

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

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

153 setattr(a, _name_, n) 

154 

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

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

157 ''' 

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

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

160 

161 def INDEX(self, name=NN, i=None, **name_i): 

162 '''Return C{"B{name}" if B{i} is None else "B{name}[B{i}]"}. 

163 ''' 

164 if name_i: 

165 name, i = _xkwds_item2(name_i) 

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

167 

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

169 '''Return C{"no convergence (B{_d})"}, C{"no convergence 

170 (B{_d}), tolerance (B{tol})"} or C{"no convergence 

171 (B{_d}), threshold (B{tol})"}. 

172 ''' 

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

174 if tol: 

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

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

177 t = t.replace(_tolerance_, _threshold_) 

178 return _no_(t) 

179 

180 def repr_at(self, inst, text=NN): 

181 '''Return a C{repr} string C{"<B{text} at B{hex_id}>"}. 

182 ''' 

183 return self.ANGLE(_SPACE_((text or inst), _at_, hex(id(inst)))) 

184 

185Fmt = Fmt() # PYCHOK singleton 

186Fmt.__name__ = Fmt.__class__.__name__ 

187 

188_DOTSTAR_ = Fmt.DOT(_STAR_) 

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

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

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

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

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

194 

195 

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

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

198 

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

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

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

202 

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

204 

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

206 intermediate whitespace characters are coalesced and 

207 substituted. 

208 ''' 

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

210 for c in n: 

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

212 s = s.replace(c, _SPACE_) 

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

214 

215 

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

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

218 formatted by function L{fstr}. 

219 

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

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

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

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

224 

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

226 of C{str}s. 

227 ''' 

228 def _items(inst, names, Nones): 

229 for n in names: 

230 v = getattr(inst, n, None) 

231 if Nones or v is not None: 

232 yield n, v 

233 

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

235 return Nones, kwds 

236 

237 Nones, kwds = _Nones_kwds(**Nones_True__pairs_kwds) 

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

239 

240 

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

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

243 

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

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

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

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

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

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

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

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

252 

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

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

255 

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

257 

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

259 ''' 

260 t = extras 

261 try: # like .dms.compassPoint 

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

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

264 if w > 0: 

265 f = 10**p # truncate 

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

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

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

269 else: # prec <= -_EN_WIDE 

270 t += (NN, NN) 

271 except (TypeError, ValueError) as x: 

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

273 return t 

274 

275if enstr2.__doc__: # PYCHOK expected 

276 enstr2.__doc__ %= (_EN_WIDE,) 

277 

278 

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

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

281 ''' 

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

283 if _DOT_ in s: 

284 m = 1 # meter 

285 else: 

286 s += _0_ * wide 

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

288 return float(s), m 

289 

290 e, m = _s2m2(estr, 0) 

291 n, m = _s2m2(nstr, m) 

292 if not m: 

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

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

295 return e, n, m 

296 

297 

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

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

300 

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

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

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

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

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

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

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

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

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

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

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

312 C{repr}, C{str}) or C{None} to raise a TypeError and used 

313 only if C{B{force} is not True}. 

314 @kwarg force: If C{True} format all B{C{floats}} using B{C{fmt}}, 

315 otherwise use B{C{strepr}} for non-C{floats}. 

316 

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

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

319 ''' 

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

321 return next(_streprs(prec, (floats,), fmt, ints, force, strepr)) 

322 else: 

323 return sep.join(_streprs(prec, floats, fmt, ints, force, strepr)) 

324 

325 

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

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

328 t = inst.easting, inst.northing 

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

330 T = _E_, _N_ 

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

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

333 T += _H_, 

334 return t, T 

335 

336 

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

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

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

340 if toRepr: 

341 n = inst.name 

342 if n: 

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

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

345 return t 

346 

347 

348def fstrzs(efstr, ap1z=False): 

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

350 

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

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

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

354 

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

356 ''' 

357 s = efstr.find(_DOT_) 

358 if s >= 0: 

359 e = efstr.rfind(Fmt.e) 

360 if e < 0: 

361 e = efstr.rfind(Fmt.E) 

362 if e < 0: 

363 e = len(efstr) 

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

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

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

367 

368 elif ap1z: 

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

370 # point and all trailing zeros, ... 

371 if efstr.isdigit(): 

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

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

374 e = efstr.rfind(Fmt.e) 

375 if e < 0: 

376 e = efstr.rfind(Fmt.E) 

377 if e > 0: 

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

379 

380 return efstr 

381 

382 

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

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

385 

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

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

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

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

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

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

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

393 ''' 

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

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

396 

397 

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

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

400 

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

402 @arg args: Optional positional arguments. 

403 @kwarg kwds: Optional keyword arguments. 

404 

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

406 ''' 

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

408 

409 

410def lrstrip(txt, lrpairs=_LR_PAIRS): 

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

412 

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

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

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

416 

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

418 ''' 

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

420 while _n(txt) > 2: 

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

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

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

424 break # restart 

425 else: 

426 return txt 

427 

428 

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

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

431 

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

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

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

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

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

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

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

439 

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

441 ''' 

442 try: 

443 if isinstance(items, dict): 

444 items = itemsorted(items) 

445 elif not islistuple(items): 

446 items = tuple(items) 

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

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

449 except (TypeError, ValueError): 

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

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

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

453 

454 

455def _pct(fmt): 

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

457 ''' 

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

459 

460 

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

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

463 

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

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

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

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

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

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

470 

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

472 ''' 

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

474 

475 

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

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

478 ''' 

479 try: 

480 r = int(_log10(resolution)) 

481 if _EN_WIDE < r or r < -_EN_PREC: 

482 raise ValueError 

483 except (ValueError, TypeError): 

484 raise Error(resolution=resolution) 

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

486 

487 

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

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

490 ''' 

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

492 if fmt in _FfEeGg: 

493 fGg = fmt in _Gg 

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

495 

496 elif fmt.startswith(_PERCENT_): 

497 fGg = False 

498 try: # to make sure fmt is valid 

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

500 _ = f % (_0_0,) 

501 except (TypeError, ValueError): 

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

503 fmt = f 

504 

505 else: 

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

507 

508 for i, o in enumerate(objs): 

509 if force or isinstance(o, float): 

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

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

512 _0_).endswith(_DOT_): 

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

514 elif prec > 1: 

515 t = fstrzs(t, ap1z=fGg) 

516 elif strepr: 

517 t = strepr(o) 

518 else: 

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

520 raise TypeError(_SPACE_(t, _not_scalar_)) 

521 yield t 

522 

523 

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

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

526 

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

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

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

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

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

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

533 

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

535 ''' 

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

537 

538 

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

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

541 

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

543 @arg args: Optional positional arguments. 

544 @kwarg kwds: Optional keyword arguments, except C{B{_fmt}=Fmt.g} 

545 and C{B{_ELLIPSIS}=False}. 

546 

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

548 ''' 

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

550 g, kwds = _xkwds_pop2(kwds, _fmt=Fmt.g) 

551 t = reprs(args, fmt=g) if args else () 

552 if e: 

553 t += _ELLIPSIS_, 

554 if kwds: 

555 t += pairs(itemsorted(kwds), fmt=g) 

556 n = where if isstr(where) else _dunder_nameof(where) # _NN_ 

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

558 

559 

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

561 '''(INTERNAL) Int formatter'. 

562 ''' 

563 return '%0*d' % w_i 

564 

565 

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

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

568 ''' 

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

570 if dot: 

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

572 return s 

573 

574 

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

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

577 ''' 

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

579 

580 

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

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

583 

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

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

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

587 

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

589 

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

591 or is not settable. 

592 ''' 

593 def _getattr(o, a): 

594 if hasattr(o, a): 

595 return getattr(o, a) 

596 try: 

597 n = o._DOT_(a) 

598 except AttributeError: 

599 n = Fmt.DOT(a) 

600 raise _AttributeError(o, name=n) 

601 

602 for a in attrs: 

603 s = _getattr(other, a) 

604 g = _getattr(insto, a) 

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

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

607 return insto 

608 

609 

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

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

612 ''' 

613 try: 

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

615 except Exception as x: 

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

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

618 

619# **) MIT License 

620# 

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

622# 

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

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

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

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

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

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

629# 

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

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

632# 

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

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

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

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

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

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

639# OTHER DEALINGS IN THE SOFTWARE.