feat(base): add units prop with helper setter

This commit is contained in:
izzy lyseggen
2021-01-26 10:01:45 +00:00
parent 6b4dc9a6b2
commit 90f5e7602c
2 changed files with 35 additions and 1 deletions
+11 -1
View File
@@ -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__
+24
View File
@@ -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})."
)