From 7e4267b08b7c4a8912d607dd6cd478f03086c361 Mon Sep 17 00:00:00 2001 From: Chris Date: Wed, 10 Jul 2019 19:48:29 -0400 Subject: [PATCH] feat(point): Added automatic casting to float for coordinate values As noted in other discussions, I realized that this did not significantly affect the performance of initializing objects with a lot of points. So we might as well implement this and avoid having to check it elsewhere. --- ladybug_geometry/geometry2d/pointvector.py | 13 +++++++++++-- ladybug_geometry/geometry3d/pointvector.py | 15 ++++++++++++--- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/ladybug_geometry/geometry2d/pointvector.py b/ladybug_geometry/geometry2d/pointvector.py index ed998ddf..387fbeb2 100644 --- a/ladybug_geometry/geometry2d/pointvector.py +++ b/ladybug_geometry/geometry2d/pointvector.py @@ -19,8 +19,8 @@ class Vector2D(object): def __init__(self, x=0, y=0): """Initialize 2D Vector.""" - self._x = x - self._y = y + self._x = self._cast_to_float(x) + self._y = self._cast_to_float(y) @classmethod def from_dict(cls, data): @@ -130,6 +130,15 @@ def to_dict(self): return {'x': self.x, 'y': self.y} + def _cast_to_float(self, value): + """Ensure that an input coordinate value is a float.""" + try: + number = float(value) + except (ValueError, TypeError): + raise TypeError( + 'Coordinates must be numbers. Got {}: {}.'.format(type(value), value)) + return number + @staticmethod def _rotate(vec, angle): """Hidden rotation method used by both Point2D and Vector2D.""" diff --git a/ladybug_geometry/geometry3d/pointvector.py b/ladybug_geometry/geometry3d/pointvector.py index e9e130be..e4992a9d 100644 --- a/ladybug_geometry/geometry3d/pointvector.py +++ b/ladybug_geometry/geometry3d/pointvector.py @@ -22,9 +22,9 @@ class Vector3D(object): def __init__(self, x=0, y=0, z=0): """Initialize 3D Vector.""" - self._x = x - self._y = y - self._z = z + self._x = self._cast_to_float(x) + self._y = self._cast_to_float(y) + self._z = self._cast_to_float(z) @classmethod def from_dict(cls, data): @@ -135,6 +135,15 @@ def to_dict(self): 'y': self.y, 'z': self.z} + def _cast_to_float(self, value): + """Ensure that an input coordinate value is a float.""" + try: + number = float(value) + except (ValueError, TypeError): + raise TypeError( + 'Coordinates must be numbers. Got {}: {}.'.format(type(value), value)) + return number + @staticmethod def _reflect(vec, normal): """Hidden reflection method used by both Point3D and Vector3D."""