@@ -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
7278cdef _is_dimensionless_zero(WithUnit u):
7379 return (u._is_dimensionless() and
@@ -575,6 +581,20 @@ cdef class WithUnit:
575581 return self .__with_value(self .value[key])
576582 except NotTUnitsLikeError:
577583 return NotImplemented
584+ except TypeError :
585+ try :
586+ unit_val = _try_interpret_as_with_unit(str (key), True )
587+ except :
588+ raise NotTUnitsLikeError(" Bad unit key: " + repr (key))
589+ if unit_val is None :
590+ raise NotTUnitsLikeError(" Bad unit key: " + repr (key))
591+ if self .base_units != unit_val.base_units:
592+ raise UnitMismatchError(" '%s ' doesn't match '%s '." %
593+ (self , key))
594+ return (self .value
595+ * conversion_to_double(conversion_div(self .conv, unit_val.conv))
596+ / unit_val.value)
597+
578598
579599 def __iter__ (self ):
580600 # Hack: We want calls to 'iter' to see that __iter__ exists and try to
@@ -688,6 +708,10 @@ cdef class WithUnit:
688708 def _from_json_dict_(cls , **kwargs ):
689709 return cls (kwargs[" value" ], kwargs[" unit" ])
690710
711+ def _resolved_value_ (self ) -> WithUnit:
712+ """Follows the cirq ResolvableValue protocol."""
713+ return self
714+
691715 def __getstate__(self ):
692716 return {
693717 ' value' : self .value,
0 commit comments