neoscore.core.units
Various interoperable units classes and some related helper functions.
- class neoscore.core.units.Unit[source]
Bases:
object
An immutable graphical distance with a unit.
Unit objects enable easy conversion from one unit to another and convenient operations between them.
Common operators (
+
,-
,/
, etc.) are supported between them. Return values from these operations are given in the type on the left.>>> from neoscore.core.units import Inch, Mm >>> print(Inch(1) + Mm(1)) Inch(1.039)
To facilitate easy comparison between equivalent values in different units, equality is checked with a tolerance of
Unit(0.001)
.>>> from neoscore.core.units import Inch, Mm >>> assert Inch(Mm(1)) == Mm(1) >>> assert Inch(Mm(1)) >= Mm(1) >>> assert Inch(Mm(1)) <= Mm(1)
The base
Unit
type is a graphical unit corresponding to 1/72nd of an inch. Internally, this is significant because it is the unit used by the graphics backend, Qt. For most purposes, you probably want to use a more descriptive unit type.- CONVERSION_RATE: float = 1
The ratio of this class to fundamental
Unit
s.Subclasses should override this.
- __init__(value: Unit | float, _raw_base_value=None)[source]
Create a unit from another unit or a raw number.
- base_value
The underlying float value in base units.
- property display_value: float
A human-friendly unit value.
If the unit was constructed with a simple number, this will return the exact given argument value. If the unit was constructed from another unit, this will return the converted value rounded to 3 decimal places.
- property rounded_base_value: float
The base value rounded to 2 decimal places.
This is useful for things like hash keys for caching purposes
- class neoscore.core.units.Inch[source]
Bases:
Unit
An inch.
- CONVERSION_RATE: float = 72
The ratio of this class to fundamental
Unit
s.Subclasses should override this.
- base_value
The underlying float value in base units.
- class neoscore.core.units.Mm[source]
Bases:
Unit
A millimeter.
- base_value
The underlying float value in base units.
- CONVERSION_RATE: float = 2.8346456664
The ratio of this class to fundamental
Unit
s.Subclasses should override this.
- neoscore.core.units.ZERO = Unit(0.0)
Shorthand for a zero unit
- neoscore.core.units.make_unit_class(name: str, conversion_rate: float) Type[Unit] [source]
Create a
Unit
subclass with a name and base unit conversion rate
- neoscore.core.units.convert_all_to_unit(collection: Union[list, dict], unit: Type[Unit])[source]
Recursively convert all numbers found in a list or dict to a unit in place.
This function works in place. Tuples and sets found within
collection
will be replaced.In dictionaries, only values are converted.