Skip to content

Commit

Permalink
Query.set_condition_units: consolidate w/ inner helper function
Browse files Browse the repository at this point in the history
  • Loading branch information
sadielbartholomew committed Nov 22, 2022
1 parent 999f827 commit 25a2184
Showing 1 changed file with 38 additions and 36 deletions.
74 changes: 38 additions & 36 deletions cf/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -858,59 +858,61 @@ def set_condition_units(self, units):
<CF Query: (ge 3000 m)>
"""
# def try_applying_units(u, val, q_units):
# try:
# val = val.copy()
# val.Units = u
# except ValueError:
# raise ValueError(
# f"Units {u!r} are not equivalent to "
# f"query condition units {q_units!r}"
# )
# return val

def get_and_set_value_units(v, u):
"""Helper method to simplify logic to set specified units."""
v_units = getattr(v, "Units", None)
if v_units is None: # Value 'v' has no units
v = Data(v, units=u)
else: # Value 'v' already has units
try:
v = v.copy()
v.Units = u
except ValueError:
raise ValueError(
f"Units {u!r} are not equivalent to "
f"query condition units {v_units!r}"
)

return v

units = Units(units)

compound = self._compound
if compound:
for r in compound:
r.set_condition_units(units)

return

value = self._value
if value is None:
return

value_units = getattr(value, "Units", None)
if value_units is None:
# Value has no units
if self.operator in ("wi", "wo", "set"):
# value is a sequence of things that may or may not
# already have units
new = []
for v in value:
v_units = getattr(v, "Units", None)
if v_units is None:
v = Data(v, units=units)
else:
try:
v = v.copy()
v.Units = units
except ValueError:
raise ValueError(
f"Units {units!r} are not equivalent to "
f"query condition units {v_units!r}"
)

new.append(v)

value = new
else:
value = Data(value, units=units)
if self.operator in ("wi", "wo", "set"):
# Value is a sequence of things that may or may not
# already have units
new_values = []
for v in value:
v = get_and_set_value_units(v, units)
new_values.append(v)

value = new_values
else:
# Value already has units
try:
value = value.copy()
value.Units = units
except ValueError:
raise ValueError(
f"Units {units!r} are not equivalent to "
f"query condition units {value_units!r}"
)
value = get_and_set_value_units(value, units)

self._value = value

self._value = value

# ----------------------------------------------------------------
# Deprecated attributes and methods
Expand Down

0 comments on commit 25a2184

Please sign in to comment.