unitcorn 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of unitcorn might be problematic. Click here for more details.

Files changed (59) hide show
  1. unitcorn/__init__.py +110 -0
  2. unitcorn/airQuality/__init__.py +99 -0
  3. unitcorn/area/__init__.py +3 -0
  4. unitcorn/area/area.py +103 -0
  5. unitcorn/base/Decorators.py +72 -0
  6. unitcorn/base/Registry.py +75 -0
  7. unitcorn/base/SmartBases.py +26 -0
  8. unitcorn/base/_Algebra.py +205 -0
  9. unitcorn/base/_Measurement.py +1122 -0
  10. unitcorn/base/_ScalingMeasurement.py +398 -0
  11. unitcorn/base/_SmartFloat.py +1635 -0
  12. unitcorn/base/__init__.py +6 -0
  13. unitcorn/config/__init__.py +318 -0
  14. unitcorn/config/__main__.py +8 -0
  15. unitcorn/config/si.toml +53 -0
  16. unitcorn/config/template.toml +146 -0
  17. unitcorn/config/us.toml +53 -0
  18. unitcorn/defaults/WeatherFlow/__init__.py +176 -0
  19. unitcorn/defaults/__init__.py +1 -0
  20. unitcorn/derived/__init__.py +16 -0
  21. unitcorn/derived/density.py +26 -0
  22. unitcorn/derived/partsPer.py +96 -0
  23. unitcorn/derived/precipitation.py +96 -0
  24. unitcorn/derived/rate.py +80 -0
  25. unitcorn/derived/volume.py +122 -0
  26. unitcorn/derived/wind.py +54 -0
  27. unitcorn/digital/__init__.py +21 -0
  28. unitcorn/energy/__init__.py +4 -0
  29. unitcorn/energy/energy.py +120 -0
  30. unitcorn/energy/power.py +83 -0
  31. unitcorn/errors/Conversion.py +12 -0
  32. unitcorn/errors/Unit.py +4 -0
  33. unitcorn/errors/__init__.py +7 -0
  34. unitcorn/length/__init__.py +19 -0
  35. unitcorn/length/imperial.py +46 -0
  36. unitcorn/length/length.py +74 -0
  37. unitcorn/length/metric.py +56 -0
  38. unitcorn/mass/__init__.py +15 -0
  39. unitcorn/mass/imperial.py +47 -0
  40. unitcorn/mass/mass.py +57 -0
  41. unitcorn/mass/metric.py +47 -0
  42. unitcorn/others/__init__.py +338 -0
  43. unitcorn/others/light.py +51 -0
  44. unitcorn/pressure/__init__.py +3 -0
  45. unitcorn/pressure/pressure.py +189 -0
  46. unitcorn/py.typed +0 -0
  47. unitcorn/temperature/__init__.py +19 -0
  48. unitcorn/temperature/celsius.py +23 -0
  49. unitcorn/temperature/change.py +156 -0
  50. unitcorn/temperature/fahrenheit.py +24 -0
  51. unitcorn/temperature/kelvin.py +25 -0
  52. unitcorn/temperature/temperature.py +154 -0
  53. unitcorn/time_/__init__.py +1 -0
  54. unitcorn/time_/time.py +387 -0
  55. unitcorn/utils.py +399 -0
  56. unitcorn-0.9.0.dist-info/METADATA +536 -0
  57. unitcorn-0.9.0.dist-info/RECORD +59 -0
  58. unitcorn-0.9.0.dist-info/WHEEL +4 -0
  59. unitcorn-0.9.0.dist-info/licenses/LICENSE.txt +17 -0
@@ -0,0 +1,1635 @@
1
+ import logging
2
+ import re
3
+ from builtins import float, isinstance
4
+ from collections import ChainMap, namedtuple
5
+ from difflib import get_close_matches
6
+ from functools import lru_cache, cached_property
7
+ from locale import delocalize, setlocale, LC_NUMERIC
8
+ from typing import ClassVar, Optional, Set, Type, Union, Tuple, ForwardRef, TypeVar, Literal, Final, Mapping, Iterable
9
+ from math import nan, isnan, inf, isinf
10
+ from decimal import Decimal
11
+
12
+ from ..errors import FormattingError
13
+ from ..utils import modifyCase, pluralize, empty, getFrom, loadUnitLocalization, CaseInsensitiveKey, DEBUG
14
+ from ..config import config, Config, GROUPING_CHAR, RADIX_CHAR
15
+ from .Registry import UnitRegistry
16
+
17
+ __all__ = ('SmartFloat', 'Limits', 'TypedLimits', 'FormatSpec', 'FiniteField', 'UnitDict', 'MetaUnitClass')
18
+
19
+ regexType: Final = Literal['b', 'c', 'd', 'e', 'E', 'f', 'F', 'g', 'G', 'n', 'o', 's', 'x', 'X', '%']
20
+
21
+ log = logging.getLogger('unitcorn').getChild('SmartFloat')
22
+
23
+ __all__ = ['SmartFloat', 'FiniteField', 'MetaUnitClass', 'FormatSpec']
24
+
25
+ Measurement = ForwardRef('Measurement', is_class=True, module='Measurement')
26
+ _T = TypeVar('_T', bound='SmartFloat')
27
+
28
+ Limits = namedtuple('Limits', 'min max')
29
+
30
+ scale_factors = (
31
+ '', 'k', 'm', 'b',
32
+ 't', 'q', 'Q', 's',
33
+ 'S', 'o', 'n', 'd',
34
+ 'U', 'D', 'T', 'Qt',
35
+ 'Qd', 'Sd', 'St', 'O',
36
+ 'N', 'v', 'c'
37
+ )
38
+
39
+
40
+ class TypedLimits(Limits):
41
+ min: _T
42
+ max: _T
43
+ _type: Type[_T] = float
44
+
45
+ @classmethod
46
+ def fromLimits(cls, limit: tuple, type: _T = float) -> 'TypedLimits':
47
+ lim = cls(*(type(x) if not isinf(x) else x for x in limit))
48
+ lim._type = type
49
+ return lim
50
+
51
+ def cast(self, type: _T) -> 'TypedLimits':
52
+ return self.fromLimits(self, type)
53
+
54
+
55
+ class FormatSpec:
56
+ truthy_values: ClassVar[Set[str]] = {'true', 't', 'yes', 'y', 'on', 'shown', 'show'}
57
+ falsy_values: ClassVar[Set[str]] = {'false', 'f', 'no', 'n', 'off', 'hidden', 'hide'}
58
+ # Parameters pasted verbatim into __format_value__'s float format spec,
59
+ # where a bool is always wrong. Without this, single-letter values that
60
+ # happen to be truthy/falsy words get coerced - `type=f` (float) and
61
+ # `type=n` (locale-aware number) both became False and produced
62
+ # '.2False'. Deliberately narrow: keys like unit_spacer/decorator/prefix/
63
+ # suffix/unit DO take False meaningfully (it disables them), so they
64
+ # must keep being coerced.
65
+ never_boolean: ClassVar[Set[str]] = {'type', 'fill', 'align', 'missing'}
66
+ # UNUSED, INTENTIONALLY KEPT. Nothing reads `.limit`, so the bracket
67
+ # syntax it describes - `{value:[100:0]}`, clamping at format time - is
68
+ # not accepted anywhere yet. Kept because implementing it is still wanted;
69
+ # the exact intent is no longer remembered, so treat the pattern as the
70
+ # specification: an optional max and an optional min, either of which may
71
+ # be `*` to mean "unbounded on this side".
72
+ limit = re.compile(r'\[(?P<max>([+-]?[\d.]+)|\*)?:(?P<min>([+-]?[\d.]+)|\*)?]')
73
+ precision = re.compile(r"""
74
+ (^)?(?(1)|(?<=:))
75
+ (?P<format_spec>
76
+ (?P<align>(?P<fill>.)?[<^>])?
77
+ (?P<sign>[-+\s])?
78
+ (?P<alt>\#)?
79
+ (?P<minwidth>\d+)?
80
+ (?P<grouping_option>[_,])?
81
+ (?P<radix>\.)?
82
+ (?(radix)(?P<precision>\d+)|)?
83
+ (?P<type>[bcdeEfFgGnosxX%])?
84
+ )
85
+ (?=:|$)
86
+ """, re.VERBOSE)
87
+ params = re.compile(r"""
88
+ (^)?(?(1)|,\s*)(
89
+ (?P<keyquote>[\'\"`]?) # optional start quote
90
+ (?P<key>\S+?) # key
91
+ (?P=keyquote) # end quote
92
+ )
93
+ \s*[=:]\s* # separator: '=' or ':' (both are written in
94
+ # the wild - `show_unit=False` vs the
95
+ # `show_unit: True` / `cardinal: False` style
96
+ # used by .withUnit and Direction.__str__.
97
+ # Only ':' was ever unsupported, so those
98
+ # specs silently parsed as nothing and the
99
+ # whole parameter was dropped.
100
+ #
101
+ # `,\s*`, not `,\s`: a bare comma separates
102
+ # as well as a comma and a space, and demanding
103
+ # the space meant `precision=0,show_unit=False`
104
+ # parsed as ONE parameter - the second was
105
+ # dropped silently, so the spec did less than
106
+ # it said, with no error.
107
+ (
108
+ (?P<valquote>[\'\"`]?) # optional start quote
109
+ (?P<value>.*?) # literal value
110
+ (?P=valquote) # end quote
111
+ )
112
+ (?=,|$)
113
+ """, re.VERBOSE)
114
+ formatParams = re.compile(r"{(?P<name>\w+?) (?: :(?P<spec>.*?))?}", re.VERBOSE)
115
+ attrRef = re.compile(r'{(?P<obj>\w+)\.(?P<attr>[\w.]+\w)(:.+?)?}')
116
+ conversion = re.compile(r"""
117
+ ^(?P<fullmatch>
118
+ (?P<convertTo>[-\w\s/\\]+)
119
+ (?P<delinator>:{1,2})?)
120
+ (?P<rest>
121
+ (?(delinator) # Test for delinator
122
+ (?: # if True
123
+ # Option 1: [:][any
124
+ (?:[-\w\s/\\]+?:).*$
125
+ | # or
126
+ # Option 2: [::][format_spec][$]
127
+ (?:\S[^:]+?$)
128
+ )
129
+ | # else
130
+ $ # False
131
+ )
132
+ )
133
+ """, re.VERBOSE)
134
+ number = re.compile(fr"""
135
+ (?P<number>
136
+ [-+]?
137
+ ([\d{GROUPING_CHAR}]+)?
138
+ ([{RADIX_CHAR}]\d+)?)
139
+ """, re.VERBOSE)
140
+ true = re.compile(rf'^({"|".join(truthy_values)})$', re.IGNORECASE)
141
+ false = re.compile(rf'^({"|".join(falsy_values)})$', re.IGNORECASE)
142
+
143
+ valueParams = re.compile(rf'(value|self):{precision.pattern}', re.VERBOSE)
144
+
145
+ @classmethod
146
+ def _float(cls, s: str | float | int) -> Optional[float | int]:
147
+ try:
148
+ value = float(delocalize(str(s)))
149
+ return int(value) if value.is_integer() else value
150
+ except ValueError:
151
+ return None
152
+
153
+ @classmethod
154
+ def getNumber(cls, value: str, strict: bool = True, default: Optional[float] = None) -> Optional[float]:
155
+ """
156
+ Get a number from a string.
157
+ :param value: string to get number from:
158
+ :param strict: Only return value if the string is entirely numeric:
159
+ :return: float or None
160
+ """
161
+
162
+ if strict:
163
+ value = cls._float(value)
164
+ return value if value is not None else default
165
+ results = next((i.groupdict() for i in cls.number.search(value) if i is not None or i != ''), None)
166
+ return cls._float(results['number']) if results else default
167
+
168
+ @classmethod
169
+ def getBool(cls, value: str, strict: bool | None = True, default: Optional[bool] = None) -> Optional[bool]:
170
+ """
171
+ Get a boolean from a string.
172
+ :param value: string to get boolean from
173
+ :param strict: Only return value if the string is entirely boolean
174
+ :param default: Default value if the string is not boolean
175
+ :return: bool or None
176
+ """
177
+ value = value.lower()
178
+
179
+ if strict:
180
+ isTrue = cls.true.match(value)
181
+ isFalse = cls.false.match(value)
182
+
183
+ if isTrue == isFalse:
184
+ return default
185
+ if isTrue is not None:
186
+ return True
187
+ elif isFalse is not None:
188
+ return False
189
+ else:
190
+ return default
191
+
192
+ elif strict is None:
193
+ hasTrue = value in cls.truthy_values
194
+ hasFalse = value in cls.falsy_values
195
+ else:
196
+ hasTrue = any(i == value for i in cls.truthy_values)
197
+ hasFalse = any(i == value for i in cls.falsy_values)
198
+
199
+ if hasTrue == hasFalse:
200
+ return default
201
+ return hasTrue
202
+
203
+
204
+ @lru_cache(maxsize=512)
205
+ def _parseSpec(formatSpec: str, numericLocale: str) -> tuple[dict, dict]:
206
+ """Split a format spec into its python format-spec part and its `key=value` parameters.
207
+
208
+ Depends only on the spec text and the numeric locale (numbers are delocalized),
209
+ so it is memoised on both. The dicts are shared: copy `specParams` before
210
+ mutating it, and treat `precisionSpec` as read-only.
211
+ """
212
+ if (precisionSpec := FormatSpec.precision.search(formatSpec)) and precisionSpec.group():
213
+ formatSpec = formatSpec[:precisionSpec.start()-1] if formatSpec.endswith(precisionSpec.group()) else formatSpec[precisionSpec.end()+1:]
214
+ precisionSpec = precisionSpec.groupdict()
215
+ else:
216
+ precisionSpec = {'format_spec': ''}
217
+
218
+ specParams = dict((i['key'], i['value']) for i in FormatSpec.params.finditer(formatSpec))
219
+ for key, value in specParams.items():
220
+ if number := FormatSpec.getNumber(value, strict=True):
221
+ specParams[key] = number
222
+ elif key in FormatSpec.never_boolean:
223
+ # Left as the literal string: several single-letter format
224
+ # codes collide with the boolean words below - 'f' and 'n'
225
+ # are both in falsy_values, so `type=f` used to coerce to
226
+ # False and reach __format_value__ as '.2False', raising
227
+ # ValueError. These keys never take a boolean value.
228
+ continue
229
+ elif (boolValue := FormatSpec.getBool(value, strict=None)) is not None:
230
+ specParams[key] = boolValue if boolValue is not None else empty
231
+ return precisionSpec, specParams
232
+
233
+
234
+ class FiniteField:
235
+ _limits: Limits
236
+
237
+ def _limitFunc(self, value: float) -> float:
238
+ return value%self._limits[1]
239
+
240
+
241
+ _MISSING: Final = object()
242
+
243
+
244
+ class FormatParams(ChainMap):
245
+ """A ChainMap with single-pass lookups.
246
+
247
+ `__format__` reads dozens of keys per call from a handful of plain dicts,
248
+ most of them misses in the first few maps. The stock implementation raises
249
+ and swallows a KeyError per missed map and checks `in` then indexes for
250
+ `get`; this probes each map once. Every map here is a plain dict, so
251
+ `dict.get` and `[]` agree.
252
+ """
253
+
254
+ def __getitem__(self, key):
255
+ for mapping in self.maps:
256
+ if (value := mapping.get(key, _MISSING)) is not _MISSING:
257
+ return value
258
+ return self.__missing__(key)
259
+
260
+ def get(self, key, default=None):
261
+ for mapping in self.maps:
262
+ if (value := mapping.get(key, _MISSING)) is not _MISSING:
263
+ return value
264
+ return default
265
+
266
+ def __contains__(self, key):
267
+ for mapping in self.maps:
268
+ if key in mapping:
269
+ return True
270
+ return False
271
+
272
+
273
+ class UnitDict(dict):
274
+
275
+ def __getitem__(self, k):
276
+ k = CaseInsensitiveKey(k)
277
+ return super().__getitem__(k)
278
+
279
+ def __setitem__(self, k, v):
280
+ k = CaseInsensitiveKey(k)
281
+ super().__setitem__(k, v)
282
+
283
+ def __delitem__(self, k) -> None:
284
+ k = CaseInsensitiveKey(k)
285
+ super().__delitem__(k)
286
+
287
+
288
+ # Bumped whenever a unit class is created or one of the attributes that
289
+ # `compatibleUnits` is built from is reassigned, so per-class caches of it can
290
+ # tell they are stale without re-walking the subclass tree on every format.
291
+ _unitGeneration: int = 0
292
+ _unitAffecting: Final = frozenset({'_unit', '_aliases', '_name', '_pluralName', '_pluralUnit', '__dimension__', '_type'})
293
+
294
+
295
+ class MetaUnitClass(type):
296
+
297
+ global Measurement
298
+
299
+ _name: ClassVar[Optional[str]]
300
+ _derived: ClassVar[bool]
301
+ _unit: ClassVar[Optional[str]] = None
302
+ _limits: ClassVar[Tuple[Union[int, float]]]
303
+ _acceptedTypes: ClassVar[Set[Type]]
304
+
305
+ class __Dimensionless__:
306
+ _dimension = None
307
+ _unit = None
308
+ _convertable = False
309
+
310
+ @property
311
+ def dimension(self):
312
+ return None
313
+
314
+ @property
315
+ def unit(self):
316
+ return ''
317
+
318
+ @property
319
+ def convertable(self):
320
+ return False
321
+
322
+ def _convert(self, *args, **kwargs):
323
+ return self
324
+
325
+ class __NonPlural__:
326
+
327
+ def __subclasscheck__(self, subclass):
328
+ return issubclass(subclass, type(self))
329
+
330
+ @property
331
+ def pluralName(self) -> None:
332
+ return None
333
+
334
+ @property
335
+ def pluralUnit(self) -> None:
336
+ return None
337
+
338
+ def __new__(mcs, name, bases, attrs, **kwargs):
339
+ if kwargs.get('baseUnit', None):
340
+ attrs['baseUnit'] = kwargs['baseUnit']
341
+
342
+ # find the Measurement name
343
+ measurementName = getFrom(
344
+ ('fullName', 'name', 'full_name', 'unitName', 'unit_name', 'unitFullName', 'unit_full_name'),
345
+ kwargs, attrs,
346
+ default=None, pop=True, expectedType=str
347
+ ) or modifyCase(name, joiner=' ')
348
+
349
+ if measurementName:
350
+ attrs['_name'] = measurementName
351
+
352
+ if aliases := getFrom(
353
+ ('aliases', 'alias', 'alternate'),
354
+ kwargs, attrs,
355
+ default=None, pop=True, findAll=True, expectedType=Iterable
356
+ ):
357
+ if isinstance(aliases, str):
358
+ aliases = (aliases,)
359
+ if aliases and isinstance(aliases, list) and not isinstance(aliases[0], str):
360
+ aliases = tuple(aliases[0])
361
+ attrs['_aliases'] = set(aliases)
362
+
363
+ # find the unit if not dimensionless
364
+ if not any([issubclass(base, mcs.__Dimensionless__) for base in bases]):
365
+ if (unit := getFrom(
366
+ ('_unit', 'unit'),
367
+ kwargs, attrs,
368
+ default=None, pop=True, expectedType=str)
369
+ ) is not None:
370
+ attrs['_unit'] = unit
371
+
372
+ # find the plurals if not non-plural
373
+ if not any([issubclass(base, mcs.__NonPlural__) for base in bases]):
374
+ if unit := attrs.get('_unit', None):
375
+ attrs['_pluralUnit'] = getFrom(
376
+ ('pluralUnit', 'plural_unit', 'plural'),
377
+ kwargs, attrs,
378
+ default=None, pop=True, expectedType=str
379
+ ) or pluralize(unit)
380
+
381
+ attrs['_pluralName'] = getFrom(
382
+ ('pluralName', 'plural_name', 'pluralFullName', 'plural_full_name'),
383
+ kwargs, attrs,
384
+ default=None, pop=True, expectedType=str
385
+ ) or pluralize(measurementName)
386
+
387
+ # set convertable if found in kwargs
388
+ if (convertable := kwargs.get('convertable', None)) is not None:
389
+ attrs['_convertable'] = convertable
390
+
391
+ if limits := getFrom(
392
+ ('limits', 'limit', 'minMax', 'min_max'),
393
+ kwargs, attrs,
394
+ default=None, pop=True, expectedType=Iterable,
395
+ findAll=False,
396
+ ):
397
+ if None in limits:
398
+ m = limits[0]
399
+ m = m if m is not None else min(getattr(mcs, '_limits', (-inf, inf)))
400
+ M = limits[1]
401
+ M = M if M is not None else max(getattr(mcs, '_limits', (-inf, inf)))
402
+ limits = sorted((m, M))
403
+ if isinstance(limits, dict):
404
+ _max = limits.get('max', None) or max(getattr(mcs, '_limits', (-inf, inf)))
405
+ _min = limits.get('min', None) or min(getattr(mcs, '_limits', (-inf, inf)))
406
+ limits = sorted(_min, _max)
407
+ attrs['_limits'] = Limits(*limits)
408
+
409
+ # load attrs from config
410
+ if name == 'Measurement':
411
+ global Measurement
412
+ attrs.update({key: value for key, value in config.unitDefaults.items() if value is not None})
413
+ # attrs['__unitDict__'] = ChainMap()
414
+ Measurement = super().__new__(mcs, name, bases, attrs, **kwargs)
415
+ return Measurement
416
+ # unitDict = ChainMap()
417
+ # for base in genericBases:
418
+ # base.__unitDict__.maps.append(unitDict)
419
+ # attrs['__unitDict__'] = unitDict
420
+
421
+ # A unit is looked up by its class name AND by its unit symbol, because
422
+ # config keys are routinely written as symbols - `inHg`, `mmHg`.
423
+ # Matching on the class name alone meant `InchOfMercury` never found
424
+ # the `inHg` line, so those settings were silently ignored.
425
+ #
426
+ # The match is exact (case-insensitively). It used to run the name
427
+ # through get_close_matches(cutoff=0.3) and take the first hit, which
428
+ # could apply a *different* unit's settings than the one that passed
429
+ # the check above.
430
+ #
431
+ # Only the class's own declared `_unit` counts, never an inherited
432
+ # one: a subclass that inherits its parent's symbol must not silently
433
+ # adopt the parent's config line.
434
+ configPropertiesKey = config.unitPropertiesKeyFor(name, attrs.get('_unit'))
435
+ if configPropertiesKey is not None:
436
+ configProps = {}
437
+ for item in config.unitProperties[configPropertiesKey].split(','):
438
+ key, value = item.strip(' ').split('=')
439
+ if (number := FormatSpec.getNumber(value, strict=True)) is not None:
440
+ value = number
441
+ elif (boolValue := FormatSpec.getBool(value, strict=False)) is not None:
442
+ value = boolValue if boolValue is not None else empty
443
+ configProps[f'_{key}'] = value
444
+ attrs.update(configProps)
445
+
446
+ attrs['__annotations__'] = ChainMap(attrs.get('__annotations__', {}), *(b.__dict__.get('__annotations__', {}) for b in bases))
447
+
448
+ global _unitGeneration
449
+ _unitGeneration += 1
450
+ mcs = super().__new__(mcs, name, bases, attrs, **kwargs)
451
+ UnitRegistry.register(mcs)
452
+ # mcs._addSpecials()
453
+ return mcs
454
+
455
+ def __setattr__(cls, key, value):
456
+ global _unitGeneration
457
+ if key in _unitAffecting:
458
+ _unitGeneration += 1
459
+ super().__setattr__(key, value)
460
+
461
+ def __delattr__(cls, key):
462
+ global _unitGeneration
463
+ if key in _unitAffecting:
464
+ _unitGeneration += 1
465
+ super().__delattr__(key)
466
+
467
+ def _addSpecials(cls):
468
+ name = cls.__name__
469
+ one = cls(1)
470
+ cls.one = one
471
+ setattr(cls.type, f'an{name.title()}', one)
472
+ setattr(cls.type, f'a{name.title()}', one)
473
+
474
+ @property
475
+ def isGeneric(cls) -> bool:
476
+ return (cls is Measurement and cls is not SmartFloat) or getattr(cls, '_type', None) is cls
477
+
478
+ @property
479
+ def genericBases(self):
480
+ return {base for base in self.__mro__ if getattr(base, 'isGeneric', False) or getattr(base, '_system', None) is base}
481
+
482
+ @property
483
+ def Generic(self) -> Type:
484
+ # Walk the MRO, not the `genericBases` set: a set of classes iterates in
485
+ # id order, so for a unit with several generic ancestors (Kilometer is a
486
+ # Length and a Measurement) `Generic` was a different one from run to run
487
+ # and `[Units] length = mi` applied only about half the time.
488
+ return next((base for base in self.__mro__ if base is not self and base in self.genericBases), None)
489
+
490
+ def __subclasscheck__(cls, subclass):
491
+ if subclass is None:
492
+ return False
493
+ value = super().__subclasscheck__(subclass)
494
+ return value
495
+
496
+ def __lt__(cls, other):
497
+ try:
498
+ return cls.scale.__lt__(other.scale)
499
+ except AttributeError:
500
+ return super().__lt__(cls, other)
501
+
502
+ def __gt__(cls, other):
503
+ try:
504
+ return cls.scale.__gt__(other.scale)
505
+ except AttributeError:
506
+ return super().__gt__(cls, other)
507
+
508
+ def __le__(cls, other):
509
+ try:
510
+ return cls.scale.__le__(other.scale)
511
+ except AttributeError:
512
+ return super().__le__(cls, other)
513
+
514
+ def __ge__(cls, other):
515
+ try:
516
+ return cls.scale.__ge__(other.scale)
517
+ except AttributeError:
518
+ return super().__ge__(cls, other)
519
+
520
+ @property
521
+ @lru_cache(maxsize=128)
522
+ def localizedUnit(self) -> Type['Measurement'] | Tuple[Type['Measurement'] | None, ...] | None:
523
+ unit = self.__parse_unit__(loadUnitLocalization(self, config))
524
+ if isinstance(unit, (tuple, list)):
525
+ if '*' in unit:
526
+ if unit[0] == '*':
527
+ unit = self.numerator, self.__findUnitClass__(unit[1])
528
+ if unit[1] == '*':
529
+ unit = self.__findUnitClass__(unit[0]), self.denominator
530
+ return unit
531
+ else:
532
+ return tuple(self.__findUnitClass__(i) for i in unit)
533
+ return self.__findUnitClass__(unit)
534
+
535
+ def __parse_unit__(self, unit: str) -> str:
536
+ return unit
537
+
538
+ @property
539
+ def isDerived(cls) -> bool:
540
+ if not hasattr(cls, '_derived'):
541
+ cls._derived = getattr(cls.__parent_class__, 'isDerived', None)
542
+ return cls._derived
543
+
544
+ @property
545
+ def isScaling(cls) -> bool:
546
+ return hasattr(cls, '_Scale')
547
+
548
+ @property
549
+ def __parent_class__(cls) -> Measurement:
550
+ return cls.__mro__[1]
551
+
552
+ @property
553
+ def type(cls) -> Type[Measurement]:
554
+ return getattr(cls, '_type', None) or next((base for base in cls.__mro__ if getattr(base, 'isGeneric', False)), cls)
555
+
556
+ @property
557
+ def dimension(self):
558
+ return getattr(self, '__dimension__', None)
559
+
560
+ @property
561
+ def subTypes(cls):
562
+ subs: Set[Type['Measurement']] = set()
563
+ for sub in cls.__subclasses__():
564
+ if sub.dimension == cls.dimension:
565
+ subs.add(sub)
566
+ subs.update(getattr(sub, 'subTypes', set()))
567
+ return subs
568
+
569
+ @property
570
+ def unit(cls) -> str:
571
+ return cls._unit or ''
572
+
573
+ @property
574
+ def system(self):
575
+ return getattr(self, '_system', None)
576
+
577
+ @property
578
+ def name(self):
579
+ return getattr(self, '_name', self.__name__)
580
+
581
+ @property
582
+ def unit_symbol(cls):
583
+ return cls._unit_symbol
584
+
585
+ @property
586
+ def suffix(cls):
587
+ return getattr(cls, '_suffix', '')
588
+
589
+ @property
590
+ def id(cls):
591
+ return (
592
+ cls.__dict__.get('_id', None)
593
+ or getattr(cls, '_unit', None)
594
+ or getattr(cls, '_unit_symbol', None)
595
+ or getattr(cls, '_suffix', None)
596
+ or getattr(cls, '_id', None)
597
+ or getattr(cls, 'unit', None)
598
+ or getattr(cls, 'name', None)
599
+ )
600
+
601
+ @property
602
+ def compatibleUnits(cls) -> UnitDict:
603
+ units = UnitDict()
604
+ for subtype in cls.type.subTypes:
605
+ units.update({alias.lower(): subtype for alias in (subtype.unit, *subtype.aliases) if alias})
606
+ units.pop(None, None)
607
+ return units
608
+
609
+ @property
610
+ def unitNames(cls) -> frozenset[str]:
611
+ """The keys of `compatibleUnits` plus 'auto', cached until a unit class changes."""
612
+ cached = cls.__dict__.get('_unitNamesCache')
613
+ if cached is not None and cached[0] == _unitGeneration:
614
+ return cached[1]
615
+ names = frozenset(cls.compatibleUnits) | {'auto'}
616
+ type.__setattr__(cls, '_unitNamesCache', (_unitGeneration, names))
617
+ return names
618
+
619
+ @property
620
+ def compatibleTypes(cls) -> Set[Type['Measurement']]:
621
+ return cls._acceptedTypes
622
+
623
+ @property
624
+ def fixedUnits(cls) -> tuple[Optional[Type['Measurement']], Optional[Type['Measurement']]]:
625
+ n: Type['Measurement'] = getattr(cls, '_numerator', None)
626
+ d: Type['Measurement'] = getattr(cls, '_denominator', None)
627
+ if n is not None:
628
+ n = None if n.isGeneric else n
629
+ if d is not None:
630
+ d = None if d.isGeneric else d
631
+ return n, d
632
+
633
+ @property
634
+ def limits(cls) -> Limits:
635
+ if cls.isDerived:
636
+ return getattr(cls, '_limits', None) or getattr(cls.numeratorClass, 'limits', None) or (-inf, inf)
637
+ return cls._limits
638
+
639
+ @property
640
+ def typedLimits(cls) -> TypedLimits:
641
+ return TypedLimits.fromLimits(cls.limits, type=cls)
642
+
643
+ def __repr__(cls):
644
+ if cls.isDerived:
645
+ match cls.fixedUnits:
646
+ case MetaUnitClass(), MetaUnitClass():
647
+ if '[' in cls.__name__:
648
+ return cls.__name__
649
+ return f'{cls.__name__}[{cls.numerator.__name__}/{cls.denominator.__name__}]'
650
+ case MetaUnitClass(), None:
651
+ return f'{cls.__name__}[{cls.denominator.__name__}]'
652
+ case None, MetaUnitClass():
653
+ return f'{cls.__name__}[{cls.numerator.__name__}]'
654
+ case _:
655
+ pass
656
+
657
+ if ((cls.numerator.isGeneric or cls.__parent_class__.numerator.isGeneric)
658
+ and (cls.denominator.isGeneric or cls.__parent_class__.denominator.isGeneric)):
659
+ return f'{cls.__name__}[{repr(cls.numerator)}/{repr(cls.denominator)}]'
660
+ elif cls.numerator.isGeneric or cls.__parent_class__.numerator.isGeneric:
661
+ return f'{cls.__name__}[{repr(cls.numeratorClass)}]'
662
+ elif cls.denominator.isGeneric or cls.__parent_class__.denominator.isGeneric:
663
+ return f'{cls.__name__}[{repr(cls.denominator)}]'
664
+ else:
665
+ return f'{cls.__name__}'
666
+ if cls.isGeneric:
667
+ return f'<{cls.__name__}>'
668
+ return cls.__name__
669
+
670
+ # @lru_cache(maxsize=512)
671
+ def __findUnitClass__(cls, unit: str) -> Type['Measurement'] | None:
672
+ if unit is None:
673
+ return None
674
+
675
+ if matched := UnitRegistry.get(unit):
676
+ return matched
677
+
678
+ unitDict = cls.compatibleUnits
679
+ # unitDict.update({v.__name__.lower(): v for v in unitDict.values() if v.__name__.lower() not in unitDict})
680
+ closestMatch = get_close_matches(unit.lower(), (i.lower() for i in unitDict.keys()), 1, cutoff=0.7)
681
+ if closestMatch:
682
+ return unitDict[closestMatch[0]]
683
+ return None
684
+
685
+ @property
686
+ def pluralName(self) -> Optional[str]:
687
+ return getattr(self, '_pluralName', None)
688
+
689
+ @property
690
+ def pluralUnit(self) -> Optional[str]:
691
+ return getattr(self, '_pluralUnit', None)
692
+
693
+ @property
694
+ def aliases(self) -> Set[str]:
695
+ return getattr(self, '_aliases', set()) | {self.name, self.pluralName, self.pluralUnit} - {None, ''}
696
+
697
+ def _limitFunc(cls, value: _T) -> float:
698
+ if cls.isDerived:
699
+ return cls.numerator._limitFunc(value)
700
+ return value
701
+
702
+
703
+ # The localised unit of a class comes from the config. A cached answer from an
704
+ # earlier file would outlive `config.read`, so which unit a value was shown in
705
+ # depended on whether it was first read before or after the file changed.
706
+ Config.onRead(MetaUnitClass.localizedUnit.fget.cache_clear)
707
+
708
+
709
+ class SmartFloat(float, metaclass=MetaUnitClass):
710
+ _limits = -inf, inf
711
+ _precision: int = 3
712
+ valuePrecision: int
713
+ _digit_budget: int = 4
714
+ # Where a number is a *label* rather than a reading - a dial face, an
715
+ # axis - the unit's convention drops the padding zeros a reading needs.
716
+ # `compact` in a format spec expands this, so a caller asks for it the
717
+ # same way it asks for `precision`, and a unit whose convention keeps its
718
+ # zeros (rain in inches) overrides it here instead of in config.
719
+ # Ranked BELOW any explicit spec key, so `compact, precision=2` still
720
+ # gets 2 decimals - the ask is a default for compactness, not an order.
721
+ _compact_format: Mapping[str, object] = {'trailing_zeros': 'off'}
722
+ _unit: Optional[str]
723
+ _suffix: Optional[str]
724
+ _unit_symbol: Optional[str]
725
+ _unit_spacer: Optional[Union[bool, str]]
726
+ _title: Optional[str]
727
+ _show_unit: Optional[bool]
728
+ _shorten: Optional[bool]
729
+ #: What a NaN formats as; see `missing`.
730
+ _missing: str = '\u22ef'
731
+ _k_separator: Optional[str]
732
+ _key: Optional[Union[str, Set[Union[str, Tuple[str]]]]]
733
+ _size_hint: Optional[str]
734
+ _acceptedTypes: ClassVar[tuple] = (float, int, Decimal)
735
+ __unitDict__: ChainMap[str, Type]
736
+ __transferable__: set[str] = {
737
+ 'leading_zero',
738
+ 'trailing_zeros',
739
+ 'true_zero',
740
+ 'align',
741
+ 'fill',
742
+ 'sign',
743
+ 'minwidth',
744
+ 'type',
745
+ 'unit_symbol',
746
+ 'unit_spacer',
747
+ 'unit',
748
+ 'show_unit',
749
+ 'suffix',
750
+ }
751
+
752
+ @classmethod
753
+ def noneToNan(cls, value):
754
+ if not isinstance(value, float):
755
+ try:
756
+ value = float(value)
757
+ except ValueError:
758
+ value = nan
759
+ except TypeError:
760
+ value = nan
761
+ return value
762
+
763
+ def __new__(cls, value):
764
+ return float.__new__(cls, value)
765
+
766
+ def __init__(self, value):
767
+ float.__init__(value)
768
+
769
+ @staticmethod
770
+ def intFloatLength(value: float) -> tuple[int, int]:
771
+ value = float(value)
772
+ if value.is_integer():
773
+ return len(str(int(value))), 0
774
+ elif isinf(value):
775
+ return 0, 0
776
+ f = f'{abs(value):g}'.split('.')
777
+ f = len(f[1]) if len(f) == 2 else 0
778
+ d = len(str(round(value)))
779
+ return d, f
780
+
781
+ @cached_property
782
+ def intLength(self) -> int:
783
+ return len(str(round(float(self))))
784
+
785
+ @cached_property
786
+ def floatLength(self) -> int:
787
+ value = float(self)
788
+ if value.is_integer():
789
+ return 0
790
+ return len(f'{abs(value):g}'.split('.')[1])
791
+
792
+ def _string(
793
+ self,
794
+ shorten: bool = None,
795
+ prefix: str = None,
796
+ suffix: str = None,
797
+ unit_symbol: str = None,
798
+ spacer: Union[bool, str] = None,
799
+ unit: bool = None,
800
+ maxLength: int = None,
801
+ formatSpec: str = None,
802
+ ) -> str:
803
+ """Render directly from keyword arguments, bypassing the spec parser.
804
+
805
+ INTENTIONALLY KEPT as a second way to format a value. `__format__` is
806
+ the primary path and takes a spec *string*, which has to be parsed and
807
+ validated; this takes the same knobs as plain keywords, which is the
808
+ cheaper call when the caller already has them as values - e.g. a
809
+ plugin schema carrying its own conversion/formatting settings.
810
+
811
+ No production caller today, so it is easy to break silently: the
812
+ snake_case rename turned this method's local `decorator` into
813
+ `unit_symbol` in the f-string but not in the parameter list, and every
814
+ call raised `NameError` until it was noticed. `tests/test_string_api.py`
815
+ exists so that cannot happen again.
816
+ """
817
+ if shorten is None:
818
+ shorten = getattr(self, '_shorten', False)
819
+ if prefix is None:
820
+ prefix = getattr(self, '_prefix', '')
821
+ if suffix is None:
822
+ suffix = getattr(self, '_suffix', '')
823
+ if unit_symbol is None:
824
+ unit_symbol = self.unit_symbol
825
+ if spacer is None:
826
+ spacer = getattr(self, '_unit_spacer', None)
827
+ if spacer is None:
828
+ spacer = ' ' if self._unit and not self.unit_symbol else ''
829
+ elif spacer is True:
830
+ spacer = getattr(self, '_spacer', ' ')
831
+ elif spacer is False:
832
+ spacer = ''
833
+ if unit is None:
834
+ unit = self.show_unit
835
+ if maxLength is None:
836
+ maxLength = getattr(self, '_digit_budget', 4)
837
+ if formatSpec is None:
838
+ formatSpec = getattr(self, '_format', 'g')
839
+ if shorten is None:
840
+ shorten = getattr(self, '_shorten', False)
841
+
842
+ if shorten:
843
+ c, valueFloat = 0, float(self)
844
+ numberLength = len(str(int(valueFloat)))
845
+ while numberLength > 3 and numberLength >= maxLength:
846
+ c += 1
847
+ valueFloat /= 1000
848
+ numberLength = len(str(int(valueFloat)))
849
+ valueSuffix = ['', 'k', 'm', 'B'][c]
850
+ else:
851
+ valueFloat = float(self)
852
+ c = False
853
+ valueSuffix = ''
854
+ if isnan(valueFloat):
855
+ return '???'
856
+
857
+ # TODO: Allow for precision to be overridden if number is scaled. (10,110.0 becomes 10.11k instead of 10.1k)
858
+ integerLength, floatingPointLength = self.intFloatLength(valueFloat)
859
+ if floatingPointLength == 1 and valueFloat.is_integer():
860
+ floatingPointLength = 0
861
+
862
+ stringType = 'f'
863
+
864
+ # Max amount of precision that can be displayed while keeping string under max length
865
+ intAllowedPrecision = max(0, maxLength - integerLength)
866
+ precision = min(self._precision, intAllowedPrecision)
867
+ if formatSpec == 'g':
868
+ formatSpec = f'.{max(1, precision + integerLength)}g'
869
+
870
+ if unit:
871
+ unitString = self.unit
872
+ else:
873
+ unitString = ''
874
+ # No unit means nothing to separate from, so no separator - same rule
875
+ # as __format_template__. Without this a dimensionless value rendered
876
+ # '180° ' with a trailing space.
877
+ spacer = spacer if (spacer and unitString) else ''
878
+ return f'{prefix}{valueFloat:{formatSpec}}{valueSuffix}{suffix}{unit_symbol}{spacer}{unitString}'
879
+
880
+ def __str__(self):
881
+ return f'{self}'
882
+
883
+ def __format__(self, formatSpec, **extras):
884
+ if isnan(self):
885
+ return self.__format_missing__(formatSpec, extras)
886
+ convertTo = None
887
+
888
+ if isinstance(formatSpec, dict):
889
+ params, formatSpec = formatSpec, formatSpec.get('format', '')
890
+ else:
891
+ params = {}
892
+
893
+ conversionSpecMatch = FormatSpec.conversion.search(formatSpec)
894
+ unitSet = type(self).unitNames
895
+ if conversionSpecMatch:
896
+ conversionSpecMatch = conversionSpecMatch.groupdict()
897
+ parsedUnit = type(self).__parse_unit__(conversionSpecMatch['convertTo'])
898
+ if isinstance(parsedUnit, str) and parsedUnit.lower() in unitSet:
899
+ formatSpec = re.sub(fr'{conversionSpecMatch["fullmatch"]}', '', formatSpec)
900
+ convertTo = ({parsedUnit} & unitSet).pop()
901
+ elif isinstance(parsedUnit, Iterable) and hasattr(self, 'numerator') and any(i.lower() in unitSet for i in parsedUnit):
902
+ formatSpec = re.sub(fr'{conversionSpecMatch["fullmatch"]}', '', formatSpec)
903
+ convertTo = tuple(i.lower() for i in parsedUnit if i in unitSet)
904
+
905
+ precisionSpec, specParams = _parseSpec(formatSpec, setlocale(LC_NUMERIC))
906
+ specParams = dict(specParams)
907
+
908
+ # Conversion
909
+ paramsSpecConversionMatch = type(self).__parse_unit__(specParams.get('convert', None))
910
+ paramsSpecConversion = next(iter({paramsSpecConversionMatch} & unitSet), None)
911
+ if convertTo := (convertTo or paramsSpecConversion):
912
+ if convertTo == 'auto':
913
+ if (auto := getattr(self, 'auto', None)) is not None:
914
+ value = auto
915
+ else:
916
+ raise NotImplementedError(f'No auto conversion for {self.name}')
917
+ else:
918
+ value = type(self).type.getClass(convertTo)(self)
919
+ elif convertTo or paramsSpecConversionMatch:
920
+ attemptedUnit = []
921
+ if conversionSpecMatch:
922
+ attemptedUnit.append(conversionSpecMatch['convertTo'])
923
+ if paramsSpecConversionMatch:
924
+ attemptedUnit.append(paramsSpecConversionMatch)
925
+ compatibleUnits = sorted(i.unit for i in type(self).type.subTypes)
926
+ raise NotImplementedError(f'{" or ".join(repr(u) for u in attemptedUnit)} is not a valid conversion for {self.name}. Valid conversions are: {compatibleUnits!r}')
927
+ else:
928
+ value = self
929
+
930
+ floatValue = fm if (fm := getattr(value, 'formatValue', None)) is not None else float(value)
931
+
932
+ params = FormatParams(extras, specParams, params)
933
+ params.extras = extras
934
+ params.specParams = specParams
935
+ # The caller's own precision, from either spelling - `format(v,
936
+ # 'precision=0')` or `v.__format__('', precision=0)`. Captured now:
937
+ # `extras` is the first map, so every `params['precision'] = ...`
938
+ # below writes into it and the asked-for value is gone by the time
939
+ # trailing_zeros needs it.
940
+ params.explicitPrecision = extras.get('precision', specParams.get('precision'))
941
+ params.default = value.defaultFormatParams
942
+ # `compact` is a *request* for the unit's label convention, so it
943
+ # expands here rather than at a call site: the caller writes
944
+ # `format(v, 'compact')` and the unit decides what that means.
945
+ #
946
+ # Ranked ABOVE `default` because that map is where `[UnitProperties]`
947
+ # lands - config writes onto the unit's own `defaultFormatParams`, so
948
+ # anything below it loses to `trailing_zeros=precision` and `compact`
949
+ # would be a no-op. It still sits BELOW extras and specParams, so an
950
+ # explicit key wins: `compact, precision=2` gets 2 decimals, because
951
+ # asking to be compact is not asking to override the caller. Read from
952
+ # `value` after any conversion above, so a refit unit's convention is
953
+ # the one used.
954
+ if params.get('compact', False):
955
+ compactFormat = getattr(value, '_compact_format', None)
956
+ if compactFormat:
957
+ params.maps.insert(2, dict(compactFormat))
958
+ params.maps.insert(3, params.default)
959
+
960
+ intLength, valuePrecision = value.intFloatLength(floatValue)
961
+ max_len = params.get('digit_budget', value._digit_budget)
962
+ shortened = False
963
+ if params.get('shorten', False):
964
+ starting_len = len(str(int(floatValue)))
965
+ if (best_fit := getattr(value, 'bestFit', None)) is not None:
966
+ if (fitted_value := best_fit(max_len)) is not value:
967
+ value = fitted_value
968
+ # The refit changed the unit, so the unit's own settings
969
+ # have to come with it: precision, digit_budget and
970
+ # trailing_zeros all belong to the unit being displayed,
971
+ # not the one the value started in. `params.default` was
972
+ # captured from the original above, so without this a
973
+ # Hectopascal shown as mmHg was formatted with
974
+ # Hectopascal's config while wearing mmHg's label.
975
+ # Spec parameters still outrank it - the defaults sit
976
+ # below `specParams` in the chain.
977
+ params.default = value.defaultFormatParams
978
+ params.maps[2] = params.default
979
+ floatValue = float(value)
980
+ intLength = value.intLength
981
+ precision_offset = starting_len - intLength
982
+ try:
983
+ params['precision'] += precision_offset
984
+ except TypeError:
985
+ params['precision'] = int(params['precision']) + precision_offset
986
+ valuePrecision += precision_offset
987
+ elif (auto := getattr(self, 'auto', None)) is not None:
988
+ value = auto
989
+ floatValue = float(value)
990
+ intLength = value.intLength
991
+ precision_offset = starting_len - intLength
992
+ params['precision'] += precision_offset
993
+ valuePrecision += precision_offset
994
+ else:
995
+ c = f'{floatValue:,}'.count(',')
996
+ if c:
997
+ shortened = self.precision + (2 * c)
998
+ valuePrecision += c * 2
999
+ params['precision'] += c * 2
1000
+ intLength -= c * 2
1001
+ floatValue /= 1000 ** c
1002
+ if (valueSuffix := scale_factors[c]) == value.unit:
1003
+ valueSuffix += ' '
1004
+ params['valueSuffix'] = valueSuffix
1005
+
1006
+ # update params.default to reflect the new value
1007
+ new_defaults = value.transferable_defaults
1008
+ params.default.update({k:v for k,v in value.defaultFormatParams.items() if k in new_defaults})
1009
+
1010
+ # get the formatSpec from the params['format']
1011
+ formatString = params.get('format', value.__format_template__(params))
1012
+ params.formatString = formatString
1013
+
1014
+ # get format specs from inside the param formatSpec
1015
+ if formatStringParams := FormatSpec.valueParams.search(formatString):
1016
+ formatStringParams = formatStringParams.groupdict()
1017
+ formatStringParams = {key: value for key, value in formatStringParams.items() if value is not None}
1018
+ else:
1019
+ formatStringParams = {}
1020
+
1021
+ params.maps.insert(0, formatStringParams)
1022
+ params.formatStringParams = formatStringParams
1023
+
1024
+ # get format specs from formatSpec
1025
+
1026
+ precisionSpec = {key: value for key, value in precisionSpec.items() if value is not None}
1027
+ params.maps.insert(0, precisionSpec)
1028
+ params.precisionSpec = precisionSpec
1029
+
1030
+ # find all sub format spect
1031
+ formatVarsSpecs = {i['name']: i.groupdict() for i in FormatSpec.formatParams.finditer(formatString)}
1032
+ params.formatVars = formatVarsSpecs
1033
+
1034
+ params['value'] = floatValue
1035
+ params['self'] = value
1036
+ params.maps.append(self.__dict__)
1037
+ params.dict = self.__dict__
1038
+
1039
+ # this was commented out because I don't think it is needed
1040
+ # params.maps.insert(0, formatVarsSpecs)
1041
+
1042
+ if params['type'] == 'g':
1043
+ p = int(params['precision'])
1044
+ if float(value) > 1:
1045
+ max_ = int(params['digit_budget'])
1046
+ params['value'] = floatValue = round(floatValue, min(p, valuePrecision))
1047
+ if p:
1048
+ totalLength = intLength + min(p, valuePrecision)
1049
+ params['precision'] = min(totalLength - intLength, max_) or 1
1050
+ # params['precision'] = max(min(totalLength - intLength, max_), 0) or 1z
1051
+ params['type'] = 'f'
1052
+ else:
1053
+ if shortened:
1054
+ totalLength = min(intLength + valuePrecision, max_) - intLength
1055
+ params['precision'] = min(valuePrecision, totalLength) or 1
1056
+ params['type'] = 'f'
1057
+ else:
1058
+ params['precision'] = intLength or 1
1059
+ else:
1060
+ params['type'] = 'f'
1061
+ # `max` is a display-width budget (total digits shown) and it
1062
+ # applies here too - this branch previously used `p` unclamped,
1063
+ # so `max` was inert for every value <= 1 and 0.004 rendered
1064
+ # '0.00' at max=3, max=2 AND max=1 alike.
1065
+ #
1066
+ # A sub-1 value normally spends intLength digits on its integer
1067
+ # part (the leading '0'), leaving max - intLength for decimals.
1068
+ # When leading_zero is off that '0' is never rendered, so it
1069
+ # costs nothing and the whole budget goes to decimals - which is
1070
+ # what makes a `precision=2, max=2` config coherent: '.01'
1071
+ # rather than an over-budget '0.01' or a useless '0.0'.
1072
+ max_ = int(params['digit_budget'])
1073
+ intDigits = self.__intDigits(params, floatValue, intLength, max_, p)
1074
+ params['leadingZeroDropped'] = intDigits != intLength
1075
+ params['precision'] = max(min(p, max_ - intDigits), 0)
1076
+
1077
+ # `precision` above is derived from the value's own decimal content,
1078
+ # so a value that happens to land on a whole number renders without
1079
+ # any decimals at all: a live pressure readout drifts 29.9 -> 30 ->
1080
+ # 30.1 and the panel width jumps with it. `trailing_zeros` overrides
1081
+ # that derivation with a stable width. See __resolveTrailingZeros.
1082
+ trailing = params.get('trailing_zeros', 'off')
1083
+ # Exact zero is exempt by default, because a bare '0' is meaningful:
1084
+ # it says the value is *actually* zero, where '0.0' says "not zero,
1085
+ # but rounds to it at this width". That distinction holds at default
1086
+ # settings - Inch(0) renders '0' while Inch(0.004) renders '0.0'.
1087
+ #
1088
+ # `true_zero=False` gives it up in exchange for a column that never
1089
+ # changes width, which is the better trade wherever zero is a common
1090
+ # reading rather than a catastrophe - precipitation, wind.
1091
+ padding = trailing not in (False, None, 'off')
1092
+ if padding and floatValue == 0 and params.get('true_zero', True):
1093
+ # Bare means bare: the branches above have already spent the
1094
+ # configured precision on this zero ('0.0', '0.00'), and `true_zero`
1095
+ # is the promise that padding never reaches it.
1096
+ params['precision'] = 0
1097
+ params['leadingZeroDropped'] = False
1098
+ params['type'] = 'f'
1099
+ elif padding:
1100
+ intDigits = intLength - bool(params.get('leadingZeroDropped'))
1101
+ # The configured precision, NOT params['precision'] - the latter
1102
+ # has already been clamped down to the value's own decimal count,
1103
+ # which is exactly the clamp this option exists to override. An
1104
+ # explicit `precision=` in the spec outranks the class default.
1105
+ configured = params.explicitPrecision
1106
+ if configured is None:
1107
+ configured = getattr(value, '_precision', None)
1108
+ params['precision'] = self.__resolveTrailingZeros(
1109
+ trailing,
1110
+ configured=None if configured is None else int(configured),
1111
+ fallback=int(params['precision']),
1112
+ room=max(int(params['digit_budget']) - intDigits, 0),
1113
+ )
1114
+ params['type'] = 'f'
1115
+
1116
+ # determine if a plural unit should be used
1117
+ if params.get('unit_type', 'unit') == 'name':
1118
+ unit = params.get('name', value.name)
1119
+ else:
1120
+ unit = params.get('unit', value.unit)
1121
+
1122
+ is_plural = round(floatValue, int(params['precision'])) != 1
1123
+ if is_plural:
1124
+ if params.get('plural', False) or unit == 'plural':
1125
+ unit = value.pluralUnit if params.get('unit_type', 'unit') != 'name' else type(value).pluralName
1126
+ precisionSpec['unit'] = unit
1127
+
1128
+ for key, opts in formatVarsSpecs.items():
1129
+ spec = opts['spec']
1130
+ try:
1131
+ # locals() copies the whole frame, so only take it once the cheap sources miss
1132
+ if (v := getFrom(key, value, self, params, default=_MISSING)) is _MISSING:
1133
+ v = getFrom(key, value, self, params, locals(), globals())
1134
+ except KeyError:
1135
+ raise FormattingError(f'Invalid format variable {key!r} in {formatString!r} while formatting {self!r}')
1136
+ if spec and key not in {'format', 'self', 'value'}:
1137
+ try:
1138
+ v = f'{v:{spec}}'
1139
+ except ValueError as e:
1140
+ log.error(f'Error formatting {key} with {spec}: "{e}" while formatting {self}')
1141
+ # if msg := next(iter(e.args), '').startswith('Unknown format code'):
1142
+ # t = FormatSpec.precision.search(spec).groupdict()['type']
1143
+ # spec = spec.removesuffix(t)
1144
+ v = f'{v}'
1145
+ formatVarsSpecs[key] = v
1146
+
1147
+ # params = value.__format_class__(formatSpec, params)
1148
+ formatString = value.__replace_format_attrs__(formatString, params)
1149
+
1150
+ # params = {k: v if v is not None else '' for k, v in params.items() if not k.startswith('_')}
1151
+ # for k, v in params.items():
1152
+ # if k in {'precision', 'minwidth'} and v:
1153
+ # params[k] = int(v)
1154
+
1155
+ params['value'] = value.__format_value__(params)
1156
+ # -0.04 at precision 0 is '-0': a value that rounds to zero keeps no sign
1157
+ if '-' in params['value'] and not any(c in '123456789' for c in params['value']):
1158
+ params['value'] = params['value'].replace('-', '', 1)
1159
+ if params.get('leadingZeroDropped', False):
1160
+ # leading_zero off for a value between -1 and 1: drop the '0'
1161
+ # before the radix point ('0.01' -> '.01', '-0.5' -> '-.5').
1162
+ # The precision computed above already assumed this, so the
1163
+ # digit it frees has gone to a decimal place.
1164
+ params['value'] = params['value'].replace('0.', '.', 1)
1165
+
1166
+ formattedValue = formatString.format_map(params)
1167
+
1168
+ return formattedValue
1169
+
1170
+ def __format_class__(self, formatSpec: str, formatParams: Mapping) -> dict:
1171
+ """Per-class hook to adjust format params before rendering.
1172
+
1173
+ UNUSED, INTENTIONALLY KEPT. No subclass overrides it and its only
1174
+ call site is commented out (see `# params = value.__format_class__(...)`
1175
+ above), so today it is a no-op returning its input unchanged.
1176
+
1177
+ Kept because the capability is wanted: a unit class should be able to
1178
+ apply its own formatting rules without every caller knowing about
1179
+ them. `Direction` is the shape of the use case - it currently reaches
1180
+ the same end by overriding `__format_value__` and `__format_template__`
1181
+ separately, which this hook would have covered in one place.
1182
+
1183
+ To revive: uncomment the call site and have it merge the returned
1184
+ mapping into `params`.
1185
+ """
1186
+ return formatParams
1187
+
1188
+ def __replace_format_attrs__(self, formatString: str, formatParams: Mapping) -> str:
1189
+ matches = FormatSpec.attrRef.findall(formatString)
1190
+ if not matches:
1191
+ return formatString
1192
+ # Flattening a ChainMap touches every key in every map; only pay for it when there is an attribute reference to resolve.
1193
+ formatVars = {**formatParams.get('formatVars', {}), **dict(formatParams)}
1194
+ self = formatParams.get('self', self)
1195
+ for obj, attr, *frmt in matches:
1196
+ if obj not in formatVars:
1197
+ if (attr_ := (getattr(self, obj, None))) is not None:
1198
+ formatParams[obj] = attr_
1199
+ continue
1200
+ obj = formatVars[obj]
1201
+ while '.' in attr:
1202
+ attr, sub_attr = attr.split('.', 1)
1203
+ obj = getattr(obj, attr, None)
1204
+ if obj is None:
1205
+ break
1206
+ attr = sub_attr
1207
+ value = getattr(obj, attr, obj)
1208
+ formatString = formatString.replace(f'{{{obj}.{attr}}}', str(value))
1209
+ return formatString
1210
+
1211
+ @staticmethod
1212
+ def __resolveTrailingZeros(mode, configured: int | None, fallback: int, room: int) -> int:
1213
+ """How many decimal places to render, ignoring the value's own content.
1214
+
1215
+ `precision` is normally derived per value from how many decimals that
1216
+ value actually has, which is why 30.0 renders '30' while 29.92 renders
1217
+ '29.9'. For anything read at a glance - a dashboard panel, a column of
1218
+ figures - that instability is the problem, not a feature: the width
1219
+ changes as the value crosses a whole number.
1220
+
1221
+ mode | 30.0 at precision=2, budget=5
1222
+ --------------|------------------------------
1223
+ 'off' | 30 (default; today's behaviour)
1224
+ 'precision' | 30.00 (pad to the configured precision)
1225
+ 'fill' | 30.000 (pad to whatever the budget allows)
1226
+ <int> | exactly that many places
1227
+
1228
+ `True` is accepted as an alias for 'precision', and 'off'/False/None
1229
+ all mean off - the spec parser already folds 'off' to False.
1230
+
1231
+ Every mode is capped by `room` (the budget minus the integer digits),
1232
+ so trailing zeros can never push a value over its digit budget.
1233
+ """
1234
+ if mode is True or mode == 'precision':
1235
+ target = configured if configured is not None else fallback
1236
+ elif mode == 'fill':
1237
+ target = room
1238
+ else:
1239
+ try:
1240
+ target = int(mode)
1241
+ except (TypeError, ValueError):
1242
+ target = fallback
1243
+ return max(0, min(int(target), room))
1244
+
1245
+ @staticmethod
1246
+ def __intDigits(params: Mapping, floatValue: float, intLength: int, max_: int, precision: int) -> int:
1247
+ """How many digits the integer part will actually occupy on screen.
1248
+
1249
+ Only ever differs from `intLength` for a value between -1 and 1,
1250
+ where the integer part is the lone '0' before the radix point. That
1251
+ '0' carries no information, so dropping it frees a digit of the
1252
+ `max` budget for a decimal place.
1253
+
1254
+ `leading_zero` is three-state:
1255
+
1256
+ - ``True`` - always keep it
1257
+ - ``False`` - always drop it
1258
+ - ``'auto'`` (default) - **drop it only when keeping it would render
1259
+ the value as zero, and dropping actually rescues a digit of it.**
1260
+
1261
+ That last condition matters. Keying purely off the configured
1262
+ precision drops the zero whenever the budget is tight, which buys
1263
+ nothing but a trailing zero: 0.5 became '.50' and 0.9697 became
1264
+ '.970' - same digit count, no more information, worse to read. The
1265
+ zero is only worth spending when the alternative is showing nothing
1266
+ at all, so 0.01 at a 2-digit budget becomes '.01' rather than '0.0',
1267
+ while 0.5 keeps its zero and 0.0416 at a 1-digit budget stays '0'
1268
+ (dropping would only give '.0', equally empty).
1269
+ """
1270
+ if not 0 < abs(floatValue) < 1:
1271
+ return intLength
1272
+ leading_zero = params.get('leading_zero', 'auto')
1273
+ if leading_zero is True:
1274
+ return intLength
1275
+ if leading_zero is False:
1276
+ return 0
1277
+ kept = max(min(precision, max_ - intLength), 0)
1278
+ if round(abs(floatValue), kept) != 0:
1279
+ return intLength # already shows something; nothing to gain
1280
+ dropped = max(min(precision, max_), 0)
1281
+ return 0 if round(abs(floatValue), dropped) != 0 else intLength
1282
+
1283
+ def __format_value__(self, params: Mapping) -> str:
1284
+ return '{value:{fill}{align}{sign}{minwidth}.{precision}{type}}'.format_map(params)
1285
+
1286
+ def __format_template__(self, params: Mapping) -> str:
1287
+ formatTemplate = []
1288
+
1289
+ if params.get('prefix', None):
1290
+ formatTemplate.append('{prefix}')
1291
+ value = params.get('value', None)
1292
+ if value is not False or value is not None:
1293
+ formatTemplate.append('{value}')
1294
+ if valueSuffix := params.get('valueSuffix', None):
1295
+ formatTemplate.append(f'{valueSuffix}')
1296
+ if params.get('unit_symbol', None):
1297
+ formatTemplate.append('{unit_symbol}')
1298
+ # An empty unit is not the same as an omitted one: `'' is not False`
1299
+ # passed the old check, so dimensionless units (Angle, Direction)
1300
+ # emitted the spacer before an empty string and rendered '180° '
1301
+ # with a trailing space. Nothing to separate means no separator.
1302
+ unit = params.get('unit', self.unit)
1303
+ if params.get('show_unit', self.show_unit) and unit is not False and unit:
1304
+ if params.get('unit_spacer', self.unit_spacer):
1305
+ formatTemplate.append('{unit_spacer}')
1306
+ formatTemplate.append('{unit}')
1307
+ if params.get('suffix', None):
1308
+ formatTemplate.append('{suffix}')
1309
+
1310
+ return ''.join(formatTemplate)
1311
+
1312
+ def __format_missing__(self, formatSpec, extras) -> str:
1313
+ """A NaN has no digits to shape, so the only parameter that applies is `missing`."""
1314
+ if 'missing' in extras:
1315
+ return str(extras['missing'])
1316
+ if isinstance(formatSpec, dict):
1317
+ if 'missing' in formatSpec:
1318
+ return str(formatSpec['missing'])
1319
+ elif (asked := next((i['value'] for i in FormatSpec.params.finditer(formatSpec) if i['key'] == 'missing'), None)) is not None:
1320
+ return asked
1321
+ return self.missing
1322
+
1323
+ @property
1324
+ def defaultFormatParams(self):
1325
+ return {
1326
+ 'leading_zero': self.leading_zero,
1327
+ 'trailing_zeros': self.trailing_zeros,
1328
+ 'true_zero': self.true_zero,
1329
+ 'align': '',
1330
+ 'fill': '',
1331
+ 'sign': '',
1332
+ 'minwidth': '',
1333
+ 'precision': self.precision,
1334
+ 'value': self,
1335
+ 'type': 'g',
1336
+ 'unit_symbol': self.unit_symbol,
1337
+ 'unit_spacer': self.unit_spacer,
1338
+ 'unit': self.unit,
1339
+ 'show_unit': self.show_unit,
1340
+ 'suffix': self.suffix,
1341
+ 'digit_budget': self.digit_budget,
1342
+ 'limits': self._limits,
1343
+ 'shorten': self.shorten,
1344
+ 'missing': self.missing,
1345
+ }
1346
+
1347
+ @property
1348
+ def transferable_defaults(self) -> set[str]:
1349
+ return self.__transferable__
1350
+
1351
+ @property
1352
+ def properties(self) -> dict:
1353
+ attrs = {}
1354
+ if dimension := getattr(self, 'dimension', None):
1355
+ attrs['dimension'] = dimension
1356
+ if unit := getattr(self, 'unit', None):
1357
+ attrs['unit'] = unit
1358
+ if (numerator := getattr(self, 'numerator', None)) and (denominator := getattr(self, 'denominator', None)):
1359
+ attrs['numerator'] = numerator
1360
+ attrs['denominator'] = denominator
1361
+ if suffix := getattr(self, 'suffix', None):
1362
+ attrs['suffix'] = suffix
1363
+ if decorator := getattr(self, 'unit_symbol', None):
1364
+ attrs['unit_symbol'] = decorator
1365
+ if maxLength := getattr(self, 'max', None):
1366
+ attrs['maxLength'] = maxLength
1367
+ if precision := getattr(self, '_precision', None):
1368
+ attrs['precision'] = precision
1369
+ if show_unit := getattr(self, 'show_unit', None):
1370
+ attrs['show_unit'] = show_unit
1371
+ if shorten := getattr(self, 'shorten', None):
1372
+ attrs['shorten'] = shorten
1373
+ if (limits := getattr(self, '_limits', None)) and limits != (-inf, inf):
1374
+ attrs['limits'] = limits
1375
+ return attrs
1376
+
1377
+ def __repr_value__(self) -> str:
1378
+ return f'{self: format={"{value}{unit_symbol}"}, type=g, shorten=False}'
1379
+
1380
+ if DEBUG:
1381
+
1382
+ def __repr__(self):
1383
+ properties = self.properties
1384
+ properties['shorten'] = False
1385
+ attrsString = ', '.join(f'{k}={str(v)}' for k, v in properties.items())
1386
+
1387
+ if (auto_value := getattr(self, 'auto', None)) is not None:
1388
+ if (auto_type := type(auto_value)) is not type(self):
1389
+ attrsString = f'auto={auto_value}, ' + attrsString
1390
+ else:
1391
+ auto_type = type(self)
1392
+
1393
+ if (best_fit := getattr(self, 'bestFit', None)) is not None:
1394
+ best_fit = best_fit()
1395
+ if type(best_fit) is not auto_type:
1396
+ attrsString = f'bestFit={best_fit}, ' + attrsString
1397
+
1398
+ return f'{type(self).__name__}(value={self.__repr_value__()}, {attrsString})'
1399
+
1400
+ else:
1401
+ def __repr__(self):
1402
+ return f'{type(self).__name__}({self.__repr_value__()})'
1403
+
1404
+ def __bool__(self):
1405
+ # A gap is falsy, even though it has a unit
1406
+ if isnan(self):
1407
+ return False
1408
+ return super().__bool__() or bool(self.unit)
1409
+
1410
+ def __float__(self) -> float:
1411
+ return super().__float__()
1412
+
1413
+ def __round__(self, n=None):
1414
+ value = super().__round__(n)
1415
+ value = self.__class__(value)
1416
+ value.__dict__.update(self.__dict__)
1417
+ return value
1418
+
1419
+ def __hash__(self):
1420
+ return hash(round(self, max(self._precision, 1)))
1421
+
1422
+ def __dir__(self):
1423
+ return list(self.properties) + ['__class__', '__module__', '__doc__', 'defaultFormat', 'defaultFormatParams']
1424
+
1425
+ @property
1426
+ def valueUnset(self) -> bool:
1427
+ return isnan(self)
1428
+
1429
+ @property
1430
+ def withUnit(self) -> str:
1431
+ return f'{self:show_unit: True}'
1432
+
1433
+ @property
1434
+ def withoutUnit(self) -> str:
1435
+ return f'{self:show_unit=False}'
1436
+
1437
+ @property
1438
+ def unit(self) -> str:
1439
+ if (unit := getattr(self, '_unit', None)) is None:
1440
+ return type(self).unit
1441
+ return unit
1442
+
1443
+ @unit.setter
1444
+ def unit(self, value: str):
1445
+ self._unit = value
1446
+
1447
+ @property
1448
+ def pluralUnit(self) -> str:
1449
+ if (pluralUnit := getattr(self, '_pluralUnit', None)) is None:
1450
+ return type(self).pluralUnit
1451
+ return pluralUnit
1452
+
1453
+ @pluralUnit.setter
1454
+ def pluralUnit(self, value: str):
1455
+ self._pluralUnit = value
1456
+
1457
+ @property
1458
+ def name(self):
1459
+ return getattr(self, '_name', type(self).__name__)
1460
+
1461
+ @property
1462
+ def unitArray(self) -> list[str]:
1463
+ unit = self.unit
1464
+ return [unit] if unit is not None else []
1465
+
1466
+ @property
1467
+ def suffix(self) -> Optional[str]:
1468
+ return getattr(self, '_suffix', '')
1469
+
1470
+ @property
1471
+ def int(self) -> int:
1472
+ return int(self)
1473
+
1474
+ @property
1475
+ def typedInt(self) -> '_SmartFloat':
1476
+ return self.__class__(int(self))
1477
+
1478
+ @property
1479
+ def rounded(self) -> '_SmartFloat':
1480
+ return self.__class__(round(float(self)))
1481
+
1482
+ @property
1483
+ def roundedInt(self) -> int:
1484
+ return int(round(float(self)))
1485
+
1486
+ @property
1487
+ def name(self) -> str:
1488
+ return self.__class__.__name__
1489
+
1490
+ @property
1491
+ def title(self) -> Optional[str]:
1492
+ return getattr(self, '_title', None)
1493
+
1494
+ @title.setter
1495
+ def title(self, value):
1496
+ self._title = value
1497
+
1498
+ @property
1499
+ def key(self) -> Optional[str]:
1500
+ return getattr(self, '_key', None)
1501
+
1502
+ @key.setter
1503
+ def key(self, value: str):
1504
+ self._key = value
1505
+
1506
+ @property
1507
+ def show_unit(self) -> bool:
1508
+ return getattr(self, '_show_unit', True)
1509
+
1510
+ @show_unit.setter
1511
+ def show_unit(self, value):
1512
+ self._show_unit = value
1513
+
1514
+ @property
1515
+ def leading_zero(self) -> bool:
1516
+ """Render the '0' before the radix point on values between -1 and 1.
1517
+
1518
+ Three-state, defaulting to ``'auto'``: keep the zero unless keeping it
1519
+ would cost a decimal place. 0.5 stays '0.5'; 0.01 becomes '.01'
1520
+ rather than a useless '0.0', because the zero it drops is the digit
1521
+ the hundredths place needed.
1522
+
1523
+ Force it either way per unit type in [UnitProperties] -
1524
+ ``leading_zero=True`` where the zero aids legibility at a distance,
1525
+ ``leading_zero=False`` to always reclaim the digit.
1526
+ """
1527
+ return getattr(self, '_leading_zero', 'auto')
1528
+
1529
+ @leading_zero.setter
1530
+ def leading_zero(self, value):
1531
+ self._leading_zero = value
1532
+
1533
+ @property
1534
+ def missing(self) -> str:
1535
+ """What the value shows when there is none (NaN, or None from a source): ``⋯`` by default.
1536
+
1537
+ Set like any other parameter: ``missing`` in ``[UnitDefaults]`` for every unit, per unit or unit type in
1538
+ ``[UnitProperties]`` (``humidity = missing=--``), on an instance, or in a format spec (``missing=n/a``).
1539
+ """
1540
+ return getattr(self, '_missing', '\u22ef')
1541
+
1542
+ @missing.setter
1543
+ def missing(self, value: str):
1544
+ self._missing = value
1545
+
1546
+ @property
1547
+ def trailing_zeros(self):
1548
+ """Pad decimals to a stable width instead of the value's own content.
1549
+
1550
+ By default (``'off'``) `precision` is derived per value from how many
1551
+ decimals that value actually has, so 29.92 renders '29.9' but 30.0
1552
+ renders '30' - a live readout changes width as it crosses a whole
1553
+ number. Set this where the value is read at a glance:
1554
+
1555
+ ``'precision'`` pad to the configured precision -> '30.00'
1556
+ ``'fill'`` pad to whatever the budget allows -> '30.000'
1557
+ ``<int>`` exactly that many decimal places
1558
+ ``'off'`` the derived, variable width (default)
1559
+
1560
+ Always capped by `digit_budget`, so padding can never push a value
1561
+ over its budget. ``True`` is an alias for ``'precision'``.
1562
+ """
1563
+ return getattr(self, '_trailing_zeros', 'off')
1564
+
1565
+ @trailing_zeros.setter
1566
+ def trailing_zeros(self, value):
1567
+ self._trailing_zeros = value
1568
+
1569
+ @property
1570
+ def true_zero(self) -> bool:
1571
+ """Keep an exact zero bare, even when `trailing_zeros` is padding.
1572
+
1573
+ A bare '0' carries information: it says the value is *actually* zero,
1574
+ where '0.0' says "not zero, but rounds to it at this width". At
1575
+ default settings that distinction holds - Inch(0) renders '0' while
1576
+ Inch(0.004) renders '0.0'.
1577
+
1578
+ Default ``True``, which preserves it. Set ``False`` where a column
1579
+ that never changes width matters more than the distinction, which is
1580
+ most places zero is an ordinary reading rather than an emergency -
1581
+ precipitation, wind speed, lightning strikes. Then zero pads like
1582
+ any other value: '0.00'.
1583
+
1584
+ No effect unless `trailing_zeros` is on; without it zero renders bare
1585
+ regardless.
1586
+ """
1587
+ return getattr(self, '_true_zero', True)
1588
+
1589
+ @true_zero.setter
1590
+ def true_zero(self, value):
1591
+ self._true_zero = value
1592
+
1593
+ @property
1594
+ def unit_symbol(self) -> str:
1595
+ return getattr(self, '_unit_symbol', empty)
1596
+
1597
+ @property
1598
+ def precision(self) -> int:
1599
+ _, valuePrecision = self.intFloatLength(self)
1600
+ return min(valuePrecision, getattr(self, '_precision', inf))
1601
+
1602
+ @precision.setter
1603
+ def precision(self, value):
1604
+ self._precision = value
1605
+
1606
+ @property
1607
+ def formatType(self) -> str:
1608
+ return 'g'
1609
+
1610
+ @property
1611
+ def digit_budget(self) -> int:
1612
+ return self._digit_budget
1613
+
1614
+ @digit_budget.setter
1615
+ def digit_budget(self, value: int):
1616
+ self._digit_budget = value
1617
+
1618
+ @property
1619
+ def shorten(self) -> bool:
1620
+ return getattr(self, '_shorten', False)
1621
+
1622
+ @shorten.setter
1623
+ def shorten(self, value):
1624
+ self._shorten = value
1625
+
1626
+ @property
1627
+ def unit_spacer(self):
1628
+ spacer = getattr(self, '_unit_spacer', False)
1629
+ if isinstance(spacer, str):
1630
+ return spacer
1631
+ return " " if spacer else ""
1632
+
1633
+ @unit_spacer.setter
1634
+ def unit_spacer(self, value):
1635
+ self._unit_spacer = value