Skip to content

Commit b27cba3

Browse files
support string comparison
1 parent 5cea66f commit b27cba3

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

tunits/core/cython/with_unit.pyx

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,13 @@ def _in_WithUnit(obj) -> raw_WithUnit:
6767
"""
6868
if isinstance(obj, WithUnit):
6969
return obj
70-
return raw_WithUnit(obj, identity_conversion(), _EmptyUnit, _EmptyUnit, Value, ValueArray)
70+
try:
71+
return raw_WithUnit(obj, identity_conversion(), _EmptyUnit, _EmptyUnit, Value, ValueArray)
72+
except NotTUnitsLikeError as e:
73+
if isinstance(obj, str):
74+
return _try_interpret_as_with_unit(obj)
75+
raise e
76+
7177

7278
cdef _is_dimensionless_zero(WithUnit u):
7379
return (u._is_dimensionless() and
@@ -575,6 +581,17 @@ cdef class WithUnit:
575581
return self.__with_value(self.value[key])
576582
except NotTUnitsLikeError:
577583
return NotImplemented
584+
except TypeError:
585+
unit_val = _try_interpret_as_with_unit(str(key), True)
586+
if unit_val is None:
587+
return NotImplemented
588+
if self.base_units != unit_val.base_units:
589+
raise UnitMismatchError("'%s' doesn't match '%s'." %
590+
(self, key))
591+
return (self.value
592+
* conversion_to_double(conversion_div(self.conv, unit_val.conv))
593+
/ unit_val.value)
594+
578595

579596
def __iter__(self):
580597
# Hack: We want calls to 'iter' to see that __iter__ exists and try to
@@ -688,6 +705,10 @@ cdef class WithUnit:
688705
def _from_json_dict_(cls, **kwargs):
689706
return cls(kwargs["value"], kwargs["unit"])
690707

708+
def _resolved_value_(self) -> WithUnit:
709+
"""Follows the cirq ResolvableValue protocol."""
710+
return self
711+
691712
def __getstate__(self):
692713
return {
693714
'value': self.value,

0 commit comments

Comments
 (0)