1

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

3

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

5'''

6

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

8 _zip, _0_0

9# from pygeodesy.constants import _0_0

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

11 _ValueError, _xkwds_get, _xkwds_item2, _xkwds_pop2

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

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

14 _N_, _name_, _not_, _not_scalar_, _PERCENT_, \

15 _SPACE_, _STAR_, _UNDER_, _dunder_nameof

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

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

18 _tolerance_ # PYCHOK used!

19 from pygeodesy.lazily import _ALL_LAZY, _ALL_MODS as _MODS

20

21 from math import fabs, log10 as _log10

22

23__all__ = _ALL_LAZY.streprs

24__version__ = '24.05.04'

25

26_at_ = 'at' # PYCHOK used!

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

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

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

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

31_RESIDUAL_ = 'RESIDUAL' # PYCHOK used!

32_threshold_ = 'threshold' # PYCHOK used!

33

34

35 class _Fmt(str):

36 '''(INTERNAL) Callable formatting.

37 '''

38 name = NN

39

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

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

42 just a single C{value}.

43 '''

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

45 break

46 else:

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

48 (NN, (name_value_ or MISSING))

49 t = str.__mod__(self, v)

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

51

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

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

54# '''

55# return str.__mod__(self, arg)

56

57

58 class Fstr(str):

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

60 '''

61 name = NN

62

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

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

65 '''

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

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

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

69 return t

70

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

72 '''Regular C{%} operator.

73

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

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

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

77

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

79

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

81 '''

82 def _error(arg):

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

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

85

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

87 if islistuple(arg):

88 n = len(arg)

89 if n == 1:

90 arg = arg[0]

91 elif n == 2:

92 prec, arg = arg

93 else:

94 raise _ValueError(_error(arg))

95

96 if not isscalar(arg):

97 raise _TypeError(_error(arg))

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

99

100

101 class _Sub(str):

102 '''(INTERNAL) Class list formatter.

103 '''

104 # see .ellipsoidalNvector.LatLon.deltaTo

105 def __call__(self, *Classes):

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

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

108

109

110 class Fmt(object):

111 '''Formatting options.

112 '''

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

114 COLON = _Fmt(':%s')

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

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

117 convergence = _Fmt(_convergence_(_PAREN_g))

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

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

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

121 e = Fstr(_e_)

122 E = Fstr(_E_)

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

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

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

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

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

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

129 f = Fstr(_f_)

130 F = Fstr(_F_)

131 g = Fstr(_g_)

132 G = Fstr('G')

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

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

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

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

137 PAREN_g = _Fmt(_PAREN_g)

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

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

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

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

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

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

144 TAG = ANGLE

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

146 tolerance = _Fmt(_tolerance_(_PAREN_g))

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

148

149 def __init__(self):

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

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

152 setattr(a, _name_, n)

153

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

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

156 '''

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

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

159

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

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

162 '''

163 if name_i:

164 name, i = _xkwds_item2(name_i)

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

166

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

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

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

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

171 '''

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

173 if tol:

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

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

176 t = t.replace(_tolerance_, _threshold_)

177 return _no_(t)

178

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

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

181 '''

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

183

184 Fmt = Fmt() # PYCHOK singleton

185 Fmt.__name__ = Fmt.__class__.__name__

186

187_DOTSTAR_ = Fmt.DOT(_STAR_)

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

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

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

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

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

193

194

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

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

197

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

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

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

201

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

203

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

205 intermediate whitespace characters are coalesced and

206 substituted.

207 '''

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

209 for c in n:

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

211 s = s.replace(c, _SPACE_)

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

213

214

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

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

217 formatted by function L{fstr}.

218

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

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

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

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

223

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

225 of C{str}s.

226 '''

227 def _items(inst, names, Nones):

228 for n in names:

229 v = getattr(inst, n, None)

230 if Nones or v is not None:

231 yield n, v

232

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

234 return Nones, kwds

235

236 Nones, kwds = _Nones_kwds(**Nones_True__pairs_kwds)

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

238

239

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

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

242

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

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

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

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

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

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

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

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

251

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

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

254

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

256

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

258 '''

259 t = extras

260 try: # like .dms.compassPoint

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

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

263 if w > 0:

264 f = 10**p # truncate

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

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

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

268 else: # prec <= -_EN_WIDE

269 t += (NN, NN)

270 except (TypeError, ValueError) as x:

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

272 return t

273

274 if enstr2.__doc__: # PYCHOK expected

275 enstr2.__doc__ %= (_EN_WIDE,)

276

277

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

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

280 '''

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

282 if _DOT_ in s:

283 m = 1 # meter

284 else:

285 s += _0_ * wide

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

287 return float(s), m

288

289 e, m = _s2m2(estr, 0)

290 n, m = _s2m2(nstr, m)

291 if not m:

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

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

294 return e, n, m

295

296

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

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

299

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

315

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

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

318 '''

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

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

321 else:

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

323

324

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

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

327 t = inst.easting, inst.northing

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

329 T = _E_, _N_

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

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

332 T += _H_,

333 return t, T

334

335

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

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

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

339 if toRepr:

340 n = inst.name

341 if n:

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

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

344 return t

345

346

347 def fstrzs(efstr, ap1z=False):

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

349

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

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

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

353

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

355 '''

356 s = efstr.find(_DOT_)

357 if s >= 0:

358 e = efstr.rfind(Fmt.e)

359 if e < 0:

360 e = efstr.rfind(Fmt.E)

361 if e < 0:

362 e = len(efstr)

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

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

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

366

367 elif ap1z:

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

369 # point and all trailing zeros, ...

370 if efstr.isdigit():

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

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

373 e = efstr.rfind(Fmt.e)

374 if e < 0:

375 e = efstr.rfind(Fmt.E)

376 if e > 0:

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

378

379 return efstr

380

381

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

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

384

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

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

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

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

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

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

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

392 '''

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

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

395

396

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

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

399

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

401 @arg args: Optional positional arguments.

402 @kwarg kwds: Optional keyword arguments.

403

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

405 '''

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

407

408

409 def lrstrip(txt, lrpairs=_LR_PAIRS):

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

411

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

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

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

415

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

417 '''

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

419 while _n(txt) > 2:

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

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

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

423 break # restart

424 else:

425 return txt

426

427

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

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

430

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

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

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

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

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

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

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

438

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

440 '''

441 try:

442 if isinstance(items, dict):

443 items = itemsorted(items)

444 elif not islistuple(items):

445 items = tuple(items)

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

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

448 except (TypeError, ValueError):

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

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

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

452

453

454 def _pct(fmt):

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

456 '''

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

458

459

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

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

462

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

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

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

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

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

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

469

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

471 '''

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

473

474

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

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

477 '''

478 try:

479 r = int(_log10(resolution))

480 if _EN_WIDE < r or r < -_EN_PREC:

481 raise ValueError

482 except (ValueError, TypeError):

483 raise Error(resolution=resolution)

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

485

486

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

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

489 '''

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

491 if fmt in _FfEeGg:

492 fGg = fmt in _Gg

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

494

495 elif fmt.startswith(_PERCENT_):

496 fGg = False

497 try: # to make sure fmt is valid

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

499 _ = f % (_0_0,)

500 except (TypeError, ValueError):

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

502 fmt = f

503

504 else:

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

506

507 for i, o in enumerate(objs):

508 if force or isinstance(o, float):

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

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

511 _0_).endswith(_DOT_):

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

513 elif prec > 1:

514 t = fstrzs(t, ap1z=fGg)

515 elif strepr:

516 t = strepr(o)

517 else:

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

519 raise TypeError(_SPACE_(t, _not_scalar_))

520 yield t

521

522

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

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

525

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

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

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

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

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

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

532

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

534 '''

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

536

537

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

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

540

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

542 @arg args: Optional positional arguments.

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

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

545

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

547 '''

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

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

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

551 if e:

552 t += _ELLIPSIS_,

553 if kwds:

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

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

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

557

558

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

560 '''(INTERNAL) Int formatter'.

561 '''

562 return '%0*d' % w_i

563

564

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

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

567 '''

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

569 if dot:

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

571 return s

572

573

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

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

576 '''

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

578

579

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

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

582

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

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

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

586

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

588

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

590 or is not settable.

591 '''

592 def _getattr(o, a):

593 if hasattr(o, a):

594 return getattr(o, a)

595 try:

596 n = o._DOT_(a)

597 except AttributeError:

598 n = Fmt.DOT(a)

599 raise _AttributeError(o, name=n)

600

601 for a in attrs:

602 s = _getattr(other, a)

603 g = _getattr(insto, a)

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

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

606 return insto

607

608

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

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

611 '''

612 try:

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

614 except Exception as x:

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

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

617

618# **) MIT License

619#

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

621#

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

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

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

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

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

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

628#

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

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

631#

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

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

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

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

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

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

638# OTHER DEALINGS IN THE SOFTWARE.