unitcorn 0.9.0__tar.gz

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 (60) hide show
  1. unitcorn-0.9.0/LICENSE.txt +17 -0
  2. unitcorn-0.9.0/PKG-INFO +536 -0
  3. unitcorn-0.9.0/README.md +506 -0
  4. unitcorn-0.9.0/auth.toml +0 -0
  5. unitcorn-0.9.0/pyproject.toml +47 -0
  6. unitcorn-0.9.0/src/unitcorn/__init__.py +110 -0
  7. unitcorn-0.9.0/src/unitcorn/airQuality/__init__.py +99 -0
  8. unitcorn-0.9.0/src/unitcorn/area/__init__.py +3 -0
  9. unitcorn-0.9.0/src/unitcorn/area/area.py +103 -0
  10. unitcorn-0.9.0/src/unitcorn/base/Decorators.py +72 -0
  11. unitcorn-0.9.0/src/unitcorn/base/Registry.py +75 -0
  12. unitcorn-0.9.0/src/unitcorn/base/SmartBases.py +26 -0
  13. unitcorn-0.9.0/src/unitcorn/base/_Algebra.py +205 -0
  14. unitcorn-0.9.0/src/unitcorn/base/_Measurement.py +1122 -0
  15. unitcorn-0.9.0/src/unitcorn/base/_ScalingMeasurement.py +398 -0
  16. unitcorn-0.9.0/src/unitcorn/base/_SmartFloat.py +1635 -0
  17. unitcorn-0.9.0/src/unitcorn/base/__init__.py +6 -0
  18. unitcorn-0.9.0/src/unitcorn/config/__init__.py +318 -0
  19. unitcorn-0.9.0/src/unitcorn/config/__main__.py +8 -0
  20. unitcorn-0.9.0/src/unitcorn/config/si.toml +53 -0
  21. unitcorn-0.9.0/src/unitcorn/config/template.toml +146 -0
  22. unitcorn-0.9.0/src/unitcorn/config/us.toml +53 -0
  23. unitcorn-0.9.0/src/unitcorn/defaults/WeatherFlow/__init__.py +176 -0
  24. unitcorn-0.9.0/src/unitcorn/defaults/__init__.py +1 -0
  25. unitcorn-0.9.0/src/unitcorn/derived/__init__.py +16 -0
  26. unitcorn-0.9.0/src/unitcorn/derived/density.py +26 -0
  27. unitcorn-0.9.0/src/unitcorn/derived/partsPer.py +96 -0
  28. unitcorn-0.9.0/src/unitcorn/derived/precipitation.py +96 -0
  29. unitcorn-0.9.0/src/unitcorn/derived/rate.py +80 -0
  30. unitcorn-0.9.0/src/unitcorn/derived/volume.py +122 -0
  31. unitcorn-0.9.0/src/unitcorn/derived/wind.py +54 -0
  32. unitcorn-0.9.0/src/unitcorn/digital/__init__.py +21 -0
  33. unitcorn-0.9.0/src/unitcorn/energy/__init__.py +4 -0
  34. unitcorn-0.9.0/src/unitcorn/energy/energy.py +120 -0
  35. unitcorn-0.9.0/src/unitcorn/energy/power.py +83 -0
  36. unitcorn-0.9.0/src/unitcorn/errors/Conversion.py +12 -0
  37. unitcorn-0.9.0/src/unitcorn/errors/Unit.py +4 -0
  38. unitcorn-0.9.0/src/unitcorn/errors/__init__.py +7 -0
  39. unitcorn-0.9.0/src/unitcorn/length/__init__.py +19 -0
  40. unitcorn-0.9.0/src/unitcorn/length/imperial.py +46 -0
  41. unitcorn-0.9.0/src/unitcorn/length/length.py +74 -0
  42. unitcorn-0.9.0/src/unitcorn/length/metric.py +56 -0
  43. unitcorn-0.9.0/src/unitcorn/mass/__init__.py +15 -0
  44. unitcorn-0.9.0/src/unitcorn/mass/imperial.py +47 -0
  45. unitcorn-0.9.0/src/unitcorn/mass/mass.py +57 -0
  46. unitcorn-0.9.0/src/unitcorn/mass/metric.py +47 -0
  47. unitcorn-0.9.0/src/unitcorn/others/__init__.py +338 -0
  48. unitcorn-0.9.0/src/unitcorn/others/light.py +51 -0
  49. unitcorn-0.9.0/src/unitcorn/pressure/__init__.py +3 -0
  50. unitcorn-0.9.0/src/unitcorn/pressure/pressure.py +189 -0
  51. unitcorn-0.9.0/src/unitcorn/py.typed +0 -0
  52. unitcorn-0.9.0/src/unitcorn/temperature/__init__.py +19 -0
  53. unitcorn-0.9.0/src/unitcorn/temperature/celsius.py +23 -0
  54. unitcorn-0.9.0/src/unitcorn/temperature/change.py +156 -0
  55. unitcorn-0.9.0/src/unitcorn/temperature/fahrenheit.py +24 -0
  56. unitcorn-0.9.0/src/unitcorn/temperature/kelvin.py +25 -0
  57. unitcorn-0.9.0/src/unitcorn/temperature/temperature.py +154 -0
  58. unitcorn-0.9.0/src/unitcorn/time_/__init__.py +1 -0
  59. unitcorn-0.9.0/src/unitcorn/time_/time.py +387 -0
  60. unitcorn-0.9.0/src/unitcorn/utils.py +399 -0
@@ -0,0 +1,17 @@
1
+ The MIT License (MIT)
2
+ Copyright © 2022 by Bryan Neal Garrison
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software
5
+ and associated documentation files (the “Software”), to deal in the Software without
6
+ restriction, including without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
8
+ Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or
11
+ substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
14
+ BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,536 @@
1
+ Metadata-Version: 2.4
2
+ Name: unitcorn
3
+ Version: 0.9.0
4
+ Summary: Units that convert, localize and format themselves, with weather-flavoured defaults
5
+ License: MIT
6
+ License-File: LICENSE.txt
7
+ Keywords: units,conversion,converter,localization,formatting,weather,temperature
8
+ Author: noblecloud
9
+ Author-email: git@noblecloud.io
10
+ Requires-Python: >=3.12,<3.15
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Education
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Natural Language :: English
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
23
+ Classifier: Topic :: Scientific/Engineering :: Physics
24
+ Classifier: Topic :: Software Development :: Libraries
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Classifier: Topic :: Utilities
27
+ Project-URL: Bug Tracker, https://github.com/noblecloud/unitcorn/issues
28
+ Project-URL: Repository, https://github.com/noblecloud/unitcorn
29
+ Description-Content-Type: text/markdown
30
+
31
+ # unitcorn 🦄
32
+ Units that convert, localize and format themselves. Born for weather dashboards,
33
+ good for anything you can measure.
34
+
35
+ > **Formerly WeatherUnits.** The library outgrew its name: lengths, masses, time,
36
+ > bytes and the whole derived-unit algebra are general-purpose, and the weather part
37
+ > lives in the config. `pip install WeatherUnits` still works, as a shim that installs
38
+ > unitcorn and forwards `import WeatherUnits` to it with a `DeprecationWarning` —
39
+ > see [compat/WeatherUnits](compat/WeatherUnits/README.md).
40
+
41
+ ```sh
42
+ pip install unitcorn
43
+ ```
44
+
45
+ ## Features
46
+ 🌈 Effortlessly define or extend your own units
47
+
48
+ ☀️ Change nearly every part of unit display from a TOML config file. No need for additional code.
49
+
50
+ ❄️ Localization can is as simple as adding .localize to a units variable or setting it to automatic
51
+
52
+ ## Requirements
53
+
54
+ - Python 3.12 – 3.14, no other dependencies
55
+
56
+ ## How to use
57
+
58
+ > 📐 **[Formatting reference →](docs/formatting.md)** — the format-spec
59
+ > mini-language, every parameter, how `precision`/`digit_budget` interact, and the
60
+ > known gotchas. Verified against the library; start there for anything
61
+ > display-related.
62
+
63
+ ### Unit Conversion
64
+
65
+ Conversion is as easy as using the desired unit's name or aliases as either an attribute or subscript
66
+
67
+ ```python
68
+ from unitcorn.temperature import Fahrenheit
69
+ >>> value = Fahrenheit(32)
70
+ >>> value
71
+ '32°'
72
+ >>> value.withUnit
73
+ '32°f'
74
+ >>> value['c'].withUnit
75
+ '0°c'
76
+ >>> value.celsius
77
+ '0°'
78
+ ```
79
+
80
+ ## Using a Config file
81
+
82
+ #### Loading a config file
83
+ ```python
84
+ import unitcorn as uc
85
+ uc.config.read('units.toml')
86
+ ```
87
+ A template config file can be found in [src/unitcorn/config](src/unitcorn/config/template.toml). An older `.ini` config still loads, and `python -m unitcorn.config units.ini` prints it as TOML. There are three sections in a valid config file
88
+ 1) LocalUnits: This is what defines what units you want to use for localization
89
+ 2) UnitDefaults: This section holds the default values that apply to every unit
90
+ 3) UnitProperties: Defines properties for individual units or unit systems as a whole
91
+
92
+ ### UnitDefaults
93
+ The basic rules are:
94
+
95
+ 1) Properties are specified without the leading '_'
96
+ 2) Units are specified with their lowercase names or types
97
+ 3) `""` sets a property to empty; leaving the key out leaves it unset
98
+ 4) In `[UnitProperties]`, each unit is an inline table: `mmHg = { precision = 2, digit_budget = 5 }`
99
+
100
+ #### Properties
101
+ - **precision:** The number of digits allowed to be displayed past the decimal but will not exceed `digit_budget`. Example number:
102
+
103
+ |example|3.14159m|
104
+ |-------|--------|
105
+ |0|3 m|
106
+ |1|3.1 m|
107
+ |2|3.14 m|
108
+ |3|3.142 m|
109
+
110
+ (The last decimal is *rounded*, not truncated.)
111
+
112
+ - **digit_budget:** The total number of digits that can be displayed while still showing the decimal. When the value doesn't fit, `shorten` decides how it is rescaled — either refitting to a different unit or dividing and appending a 10³ suffix.
113
+
114
+ |example|415.25mm|
115
+ |-----|-------|
116
+ |2|41.53 cm|
117
+ |3|415.2 mm|
118
+ |4|415.2 mm|
119
+ |5|415.2 mm|
120
+
121
+ ⚠️ Note the budget **caps but does not grant**: raising it above 3 does
122
+ not buy more decimals here, because `precision` is separately capped by
123
+ the class default and by the value's own decimal content. The
124
+ intuitive `4 → 415.3mm, 5 → 415.25mm` progression requires raising
125
+ `precision` too. See [the formatting reference](docs/formatting.md).
126
+
127
+ - **unit:** Override built in unit string
128
+ - **suffix:** Override built in suffix string._Only used for shortening numbers_
129
+ - **unit_symbol:** Override built in symbol trailing the value._Only used for ° with degrees_
130
+ - **title:** Title to be used by other display programs
131
+ - **exp:** Override exponent. I can't imagine why this would be used
132
+ - **show_unit:** Show unit True: 5km False: 5
133
+ - **leading_zero:** Display zero before values less than 1. `True`: 0.1in `False`: .1in `auto` (default): keeps the zero unless keeping it would cost the value its last meaningful digit — see [the formatting reference](docs/formatting.md) for the exact rule
134
+ - **trailing_zeros:** Pad decimals to a stable width instead of the value's own content. By default `precision` follows the value, so `29.92` shows `29.9` but `30.0` shows `30` — a live readout changes width as it crosses a whole number.
135
+
136
+ |value|`inHg(30.0)` at `precision=2, digit_budget=5`|
137
+ |----|------|
138
+ |`off` (default)|`30.0`|
139
+ |`precision`|`30.00`|
140
+ |`fill`|`30.000`|
141
+ |`3`|`30.000`|
142
+
143
+ (At class defaults, with no spec at all, `off` gives a bare `30` — the
144
+ derived precision is zero because the value has no decimals of its own.
145
+ That is the drift this option exists to remove.)
146
+
147
+ Always capped by `digit_budget`, so padding can never push a value over
148
+ budget. `True` is an alias for `precision`.
149
+
150
+ - **true_zero:** Keep an exact zero bare (`0`) even while `trailing_zeros` is
151
+ padding everything else. Default `True`. A bare `0` says the value is
152
+ *actually* zero, where `0.0` says "not zero, but rounds to it at this
153
+ width" — `Inch(0)` gives `0` while `Inch(0.004)` gives `0.0`. Set `False`
154
+ where a column that never changes width matters more than the distinction,
155
+ which is most places zero is an ordinary reading: precipitation, wind,
156
+ lightning strikes. No effect unless `trailing_zeros` is on.
157
+ - **unit_spacer:** The text placed between the value and its unit. ⚠️ **This is a string, not a flag** — `False` removes it (`90°f`), but `True` inserts the literal word (`90°Truef`). Leave it unset for the class default (a space), or give it the string you want.
158
+ - **k_separator:** The character separating powers of 10³ — the `,` in `1,000`. _Not yet implemented_
159
+
160
+ |value|example|
161
+ |----|------|
162
+ |True|1,000ft|
163
+ |False|1000ft|
164
+
165
+ - **shorten:** Rescales a value that doesn't fit the `digit_budget`. Does one of two things depending on the unit type: refits to a neighbouring unit, or divides and appends a 10³ suffix.
166
+
167
+ |value|example|
168
+ |----|------|
169
+ |True|16.67min|
170
+ |False|1000s|
171
+
172
+ (`Time.Second(1000)` — here it refits the unit. `Light.Lux(1000)` takes
173
+ the other branch and gives `1.00k lux`.)
174
+
175
+ - **slide:** Scale units for the appropriate values. _Not yet implemented_
176
+
177
+ |value|example|
178
+ |----|------|
179
+ |True|1km|
180
+ |False|1000m|
181
+
182
+ - **cardinal:** Show degrees as a cardinal direction rather than a number. **_shorten_** _decides full vs abbreviated name_
183
+
184
+ |value|example|
185
+ |----|------|
186
+ |True|S|
187
+ |False|180°|
188
+
189
+ With `cardinal` on, two axes work independently: **`shorten` picks the
190
+ form** (letters vs words) and **`digit_budget` picks the detail**.
191
+
192
+ The budget counts **compass components**, and the atom it counts depends
193
+ on the form — a letter when abbreviated, a word when spelled out. So the
194
+ same budget carries the same amount of information either way:
195
+
196
+ |`digit_budget`|`shorten=True`|`shorten=False`|resolves to|
197
+ |----|------|------|------|
198
+ |1|`W`|`West`|4 points|
199
+ |2|`SW`|`South West`|8 points|
200
+ |3|`WSW`|`West South West`|16 points|
201
+
202
+ The budget is a **cap, not a quota**: a heading that lands on a cardinal
203
+ doesn't pad to fill it. At a 2-component budget, 202.5° gives `S` /
204
+ `South`, not a stretched two-component form.
205
+
206
+ - **key:** Key to be used for other programs
207
+ - **size_hint:** Override generated size hint string. Useful for when you know the expected max string length.
208
+
209
+
210
+ > Every code example below is executed against the library as part of
211
+ > verifying this README — they define real, working unit classes.
212
+
213
+ ## Defining Your Own Unit
214
+
215
+ There are currently three types of unit, **Static**, **Scaling**, and **Derived**
216
+
217
+ ### Static Unit
218
+ The most simple to define. Temperature is an example of a static unit.
219
+ Similar units of the same are a subclass of the unit type. In the example below,
220
+ Fahrenheit, Celsius, and Kelvin are subclasses of Temperature. Convert to other
221
+ similar units with a single private function sharing the name of the desired unit.
222
+
223
+ ```python
224
+ from unitcorn.base import Measurement, UnitType
225
+
226
+ @UnitType # Unit types are defined with this decorator.
227
+ class Temperature(Measurement): # For static unit types, the class inherits Measurement.
228
+
229
+ # Shared unit properties are defined here or in a provided config file.
230
+ _unit_symbol = '°'
231
+
232
+ # Properties for converting units are defined in the main parent class.
233
+ @property
234
+ def fahrenheit(self):
235
+ # Unless all the subunits are defined in the same file, importing the desired
236
+ # class locally is currently necessary.
237
+ return Fahrenheit(self._fahrenheit())
238
+
239
+ # Unit abbreviations are defined somewhere below the converting property.
240
+ f = fahrenheit
241
+
242
+ @property
243
+ def celsius(self):
244
+ return Celsius(self._celsius())
245
+ c = celsius
246
+
247
+ class Fahrenheit(Temperature):
248
+ # Individual unit strings are defined as protected class variables
249
+ # for each unit or within a config file.
250
+ _unit = 'f'
251
+
252
+ # This method is what is called to convert Fahrenheit to Celsius.
253
+ def _celsius(self):
254
+ # Since Measurement is a float subclass, math can be done on self.
255
+ return (self - 32) / 1.8
256
+
257
+ def _fahrenheit(self):
258
+ # Currently, a function needs to be defined for even converting to the
259
+ # same unit to prevent errors.
260
+ return self
261
+
262
+ class Celsius(Temperature):
263
+ _unit = 'c'
264
+
265
+ def _celsius(self):
266
+ return self
267
+
268
+ def _fahrenheit(self):
269
+ return (self * 1.8) + 32
270
+ ```
271
+
272
+ ### Scaling Unit
273
+
274
+ Scaling units have quite a bit going on. A scaling unit can be reduced to a single unit through a multiplier, this is the base unit.
275
+ Multiple unit systems can be defined within one scale. It is also to split systems separate scales as long as there is a function within
276
+ each system that converts from one base unit to the other.
277
+
278
+ - **SystemVariant:** Marks a unit as falling outside the regular scale
279
+ - **Synonym:** Denotes that a unit is the same as an already defined one but uses another name. Synonym classes inherit their identically valued class
280
+ - **Dimension:** A *metaclass* for the shared dimension class (`class Length(metaclass=Dimension, symbol='L')`), which the per-system classes then inherit
281
+ - **`baseUnit=`:** A class keyword naming the base unit for the system, used when converting to a non-standard `SystemVariant`
282
+ - **`system=`:** A class keyword assigning the class to `metric`, `imperial`, or `both`
283
+ - **Scale:** Uses the metaclass EnumMeta to define the scaling factors for a ScalingMeasurement class along with the multipliers for any SystemVariants
284
+ and the base unit
285
+
286
+ To define a scaling measurement (one that has multiple units within the same unit system, think Centimeter, Meter, Kilometer)
287
+ the unit system class inherits ScalingMeasurement. The main difference from Measurement is the _Scale class defined inside the
288
+ main parent class. In the example below, two unit systems (US and SI) are defined in the same scale. Most US units
289
+ have an SI basis, so this can be done fairly often. However, it is sometimes necessary to split them for readability.
290
+
291
+ #### Unified System
292
+
293
+ ```python
294
+
295
+ from unitcorn.base import UnitType, Synonym, ScalingMeasurement
296
+ from unitcorn.base import Scale, SystemVariant, both
297
+
298
+ @UnitType
299
+ # `baseUnit` names the unit everything reduces to; `system` assigns the class
300
+ # to metric, imperial, or both.
301
+ class Pressure(ScalingMeasurement, baseUnit='Pascal', system=both):
302
+
303
+ # The scale for the unit system is defined with by a class named _Scale inheriting.
304
+ class _Scale(Scale):
305
+ # Every unit is named here starting with the smallest unit and assigned a
306
+ # scaling multiplier. Scaling multipliers here must be an integer.
307
+ Pascal = 1
308
+ Decapascal = 10
309
+ Hectopascal = 10
310
+
311
+ # A base unit is also defined denoted by Base = class.__name__.
312
+ # Base value must be a string.
313
+ Base = 'Pascal'
314
+
315
+ # System variants are units that fall outside of the normal scale
316
+ # The multiplier value for variants must be a float and be relative
317
+ # to the base unit. For example, 1 Bar is 1000 Pascals and
318
+ # 1 MillimeterOfMercury is 1/0.00750062 or 133.3 Pascals.
319
+ Bar = 1000.
320
+ Atmosphere = 101325.
321
+ PoundsPerSquareInch = 6894.757293168
322
+ MillimeterOfMercury = 1 / 0.00750062
323
+ InchOfMercury = 1 / 0.00029530
324
+
325
+ @property
326
+ def pascal(self):
327
+ return Pascal(self)
328
+
329
+ @property
330
+ def hectopascal(self):
331
+ return Hectopascal(self)
332
+
333
+ class Pascal(Pressure):
334
+ _unit = 'Pa'
335
+
336
+ class Hectopascal(Pressure):
337
+ _unit = 'hPa'
338
+
339
+ class Atmosphere(Pascal, SystemVariant):
340
+ _unit = 'atm'
341
+
342
+ @Synonym
343
+ class Millibar(Hectopascal):
344
+ _unit = 'mBar'
345
+ _digit_budget = 4
346
+ ```
347
+
348
+ #### Split system
349
+
350
+ ```python
351
+ from unitcorn.base import ScalingMeasurement, Scale, Dimension
352
+ from unitcorn.base import metric, imperial
353
+
354
+
355
+ # The shared dimension is a plain class using the Dimension metaclass. It owns
356
+ # the conversion properties; the per-system classes below supply the scales.
357
+ class Length(metaclass=Dimension, symbol='L'):
358
+
359
+ @property
360
+ def meter(self):
361
+ return Meter(self)
362
+ m = meter
363
+
364
+ @property
365
+ def foot(self):
366
+ return Foot(self)
367
+ ft = foot
368
+
369
+
370
+ class ImperialLength(ScalingMeasurement, Length, system=imperial, baseUnit='Foot'):
371
+
372
+ class _Scale(Scale):
373
+ Line = 1
374
+ Inch = 12
375
+ Foot = 12
376
+ Yard = 3
377
+ Mile = 1760
378
+ Base = 'Foot'
379
+
380
+ # Since the multipliers are defined in _Scale, changeScale() uses one
381
+ # parameter to change the scale within the same system.
382
+ def _foot(self):
383
+ return self.changeScale(self._Scale.Foot)
384
+
385
+ # This function is called to convert from ImperialLength to MetricLength. Once its
386
+ # converted to MetricLength, changeScale() is called within the MetricLength class
387
+ # to get to the final unit.
388
+ def _meter(self):
389
+ return self._foot() * 0.3048
390
+
391
+
392
+ class Foot(ImperialLength):
393
+ _unit = 'ft'
394
+
395
+
396
+ class MetricLength(ScalingMeasurement, Length, system=metric, baseUnit='Meter'):
397
+
398
+ class _Scale(Scale):
399
+ Millimeter = 1
400
+ Centimeter = 10
401
+ Decimeter = 10
402
+ Meter = 10
403
+ Decameter = 10
404
+ Hectometer = 10
405
+ Kilometer = 10
406
+ Base = 'Meter'
407
+
408
+ def _meter(self):
409
+ return self.changeScale(self._Scale.Meter)
410
+
411
+ # As with the pervious class, this method is called to convert from MetricLength
412
+ # to ImperialLength.
413
+ def _foot(self):
414
+ return self._meter() * 3.280839895013123
415
+
416
+
417
+ class Meter(MetricLength):
418
+ _unit = 'm'
419
+ ```
420
+
421
+
422
+ ### Derived Unit
423
+ DerivedMeasurement is essentially a measurement with multiple units, eg, m/s [meters per second], mph [miles per hour].
424
+ A derived value is **one number in its unit**, like every measurement. `.numerator` and `.denominator` describe it as
425
+ "this much of the numerator unit per ONE of the denominator unit", so `MilesPerHour(20).numerator` is `20 mi` and
426
+ `.denominator` is `1 hr`. Building one from an amount over an interval still works and gives the rate:
427
+ `Hourly(Millimeter(6), Hour(3))` is `2 mm/hr`. A value that has to remember the window it covers (rain in the last
428
+ 24 hours) carries `period=timedelta(...)` beside its `timestamp`; conversion never touches it.
429
+
430
+ Rates and accumulations share a number and differ in meaning (`mm/h` and `mm`, `kW` and `kWh`), so the class has to
431
+ say which one it is.
432
+
433
+ **Dimension algebra.** `*` and `/` between measurements of different dimensions work on exponent vectors over length,
434
+ mass, time and temperature:
435
+
436
+ ```python
437
+ from unitcorn import Length, Mass, Time
438
+ Meter, Foot, Millimeter, Hour, Kilogram = Length.Meter, Length.Foot, Length.Millimeter, Time.Hour, Mass.Kilogram
439
+
440
+ Meter(10) / Meter(2) # 5.0, a plain float
441
+ Millimeter(6) / Hour(3) # 2 mm/hr, keeps the units it was given
442
+ Meter(5) * Meter(5) # 25 m², an Area
443
+ Foot(3) * Meter(1) # 0.9144 m², across systems
444
+ Kilogram(2) / (Meter(2) * Meter(2) * Meter(2)) # 0.25 kg·m⁻³
445
+ ```
446
+
447
+ The result is a named type when one is registered for the dimension (length, mass, time, pressure, speed), a plain
448
+ float when it is dimensionless, and otherwise a `Compound`, which prints its coherent SI unit and takes part in
449
+ further algebra. Exponents run from -3 to 3. A temperature *reading* (`Celsius(5)`) does not multiply or divide, since
450
+ `20 °C × 2` is not `40 °C`; use `Kelvin`. Unary `-`/`+`, `%`, `//`, `round` and scalar `*` and `/` keep the class.
451
+
452
+ **Temperature readings and changes.** `Celsius(30) - Celsius(20)` is a `CelsiusChange(10)`, which is also an
453
+ `18` change in `FahrenheitChange`: a change converts by a factor, never an offset. A reading plus or minus a change is a
454
+ reading (`Fahrenheit(68) + CelsiusChange(10)` is `86 °F`). Two readings do not add, because `20 °C + 10 °C` and
455
+ `68 °F + 50 °F` are not the same temperature; inside `with summingReadings():` they add in the left operand's unit
456
+ (for a mean). A bare number next to a reading still means the same unit.
457
+
458
+ **Energy, power and area** are units in their own right: `Energy` (J, kJ, MJ, GJ, Wh, kWh, MWh, cal, BTU),
459
+ `Power` (W, kW, MW, GW, hp) and `Area` (m², cm², km², ha, in², ft², mi², ac). `Power.Kilowatt(2) * Time.Hour(3)` is
460
+ `Energy` (6 kWh), `Energy.KilowattHour(6) / Time.Hour(3)` is `Power`, and `Meter(2) * Meter(3)` is an `Area`. `Light.Irradiance` (W/m²) is power per area: `Irradiance(500) * Area.SquareMeter(20)` is
461
+ `Power` (10 kW), and `Power / Area` is an `Irradiance`. Illuminance (lux) has no dimension and does not multiply.
462
+
463
+ **Note:**
464
+ Still to do: several different units in the numerator or denominator at once, and compound units beyond what the
465
+ exponent vector names (`Compound` prints them in SI).
466
+
467
+ Roughly what `DerivedMeasurement` does, for orientation (illustrative, not
468
+ the real source):
469
+
470
+ ```python
471
+ # Illustrative sketch, not the real source.
472
+ class DerivedMeasurement(Measurement):
473
+ _numerator: Measurement
474
+ _denominator: Measurement
475
+
476
+ def __init__(self, numerator, denominator):
477
+ self._numerator = numerator
478
+ self._denominator = denominator
479
+ Measurement.__init__(self, numerator / denominator)
480
+ ```
481
+
482
+ And defining your own:
483
+
484
+ ```python
485
+ from unitcorn import Length, Time
486
+ from unitcorn.base import DerivedMeasurement, UnitType
487
+
488
+
489
+ @UnitType
490
+ # The numerator and denominator dimensions are declared as class keywords.
491
+ class DistanceOverTime(DerivedMeasurement, numerator=Length, denominator=Time):
492
+
493
+ # Currently all variations that will be used have to be defined as properties
494
+ @property
495
+ def mih(self):
496
+ converted = DistanceOverTime(self._numerator.mi, self._denominator.hr)
497
+
498
+ # Without this override, the unit would be displayed as 'mi/hr'
499
+ converted._suffix = 'mph'
500
+ return converted
501
+
502
+ @property
503
+ def ms(self):
504
+ return DistanceOverTime(self._numerator.m, self._denominator.s)
505
+
506
+ @property
507
+ def kmh(self):
508
+ return DistanceOverTime(self._numerator.km, self._denominator.hr)
509
+
510
+ mph = mih
511
+
512
+
513
+ @UnitType
514
+ class Precipitation(DistanceOverTime):
515
+
516
+ @property
517
+ def inh(self):
518
+ return Precipitation(self._numerator.inch, self._denominator.hr)
519
+
520
+ @property
521
+ def mmh(self):
522
+ return Precipitation(self._numerator.mm, self._denominator.hr)
523
+
524
+
525
+ @UnitType
526
+ class PrecipitationRate(Precipitation):
527
+ pass
528
+
529
+
530
+ # Fixing the denominator is a one-liner: no __init__ override needed.
531
+ class Daily(PrecipitationRate, denominator=Time.Day): ...
532
+
533
+
534
+ class Hourly(PrecipitationRate, denominator=Time.Hour): ...
535
+
536
+ ```