Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions measurement/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import inspect
import warnings
from functools import total_ordering
from math import floor, log10
from typing import Any, Dict, Iterable, List, Optional, Tuple, Type, Union


Expand Down Expand Up @@ -257,6 +258,22 @@ def __init__(
self.unit = self._units[unit]
self.unit.org_name = unit
self.si_value = self.unit.to_si(value)
self.units_conversor = self.units_conversor = {
float(v.factor): k for k, v in self._units.items() if len(k) <= 3
}
self.update_org_name()

def update_org_name(self):
if self.si_value == 0:
self.unit.org_name = self.units_conversor[1.0]
else:
factor = float(10 ** int((floor(log10(self.si_value) / 3) * 3)))
if factor in self.units_conversor:
self.unit.org_name = self.units_conversor[factor]
elif factor > max(self.units_conversor):
self.unit.org_name = self.units_conversor[max(self.units_conversor)]
elif factor < min(self.units_conversor):
self.unit.org_name = self.units_conversor[min(self.units_conversor)]

def __getattr__(self, name):
try:
Expand Down
3 changes: 3 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ class TestAbstractMeasure:
measure = Distance
unit = "m"

def test_update_org_name(self):
assert str(Distance("0.001 m")) == "1 mm"

def test_repr(self):
assert repr(Distance("1 km")) == 'Distance(metre="1E+3")'

Expand Down