diff --git a/speckle/objects/base.py b/speckle/objects/base.py index 723a4d3..4202859 100644 --- a/speckle/objects/base.py +++ b/speckle/objects/base.py @@ -3,7 +3,7 @@ from pydantic.main import Extra from typing import Dict, List, Optional, Any from speckle.transports.memory import MemoryTransport from speckle.logging.exceptions import SpeckleException - +from speckle.objects.units import get_units_from_string PRIMITIVES = (int, float, str, bool) @@ -13,8 +13,10 @@ class Base(BaseModel): totalChildrenCount: Optional[int] = None applicationId: Optional[str] = None speckle_type: Optional[str] = "Base" + _units: str = "m" _chunkable: Dict[str, int] = {} # dict of chunkable props and their max chunk size _chunk_size_default: int = 1000 + _detachable: List[str] = [] # list of defined detachable props def __init__(self, **kwargs) -> None: super().__init__() @@ -39,6 +41,14 @@ class Base(BaseModel): attr.__set__(self, value) super().__setattr__(name, value) + @property + def units(self): + return self._units + + @units.setter + def units(self, value: str): + self._units = get_units_from_string(value) + def to_dict(self) -> Dict: """Convenience method to view the whole base object as a dict""" base_dict = self.__dict__ diff --git a/speckle/objects/units.py b/speckle/objects/units.py new file mode 100644 index 0000000..533be79 --- /dev/null +++ b/speckle/objects/units.py @@ -0,0 +1,24 @@ +from speckle.logging.exceptions import SpeckleException + +UNITS = ["mm", "cm", "m", "in", "ft", "yd", "mi"] + +UNITS_STRINGS = { + "mm": ["mm", "mil", "millimeters", "millimetres"], + "cm": ["cm", "centimetre", "centimeter", "centimetres", "centimeters"], + "m": ["m", "meter", "meters", "metre", "metres"], + "in": ["in", "inch", "inches"], + "ft": ["ft", "foot", "feet"], + "yd": ["yd", "yard", "yards"], + "mi": ["mi", "mile", "miles"], +} + + +def get_units_from_string(unit: str): + unit = str.lower(unit) + for name, alternates in UNITS_STRINGS.items(): + if unit in alternates: + return name + + raise SpeckleException( + message=f"Could not understand what unit {unit} is referring to. Please enter a valid unit (eg {UNITS})." + )