Skip to content

Commit

Permalink
cast units to str before applying any other preprocessor (#498)
Browse files Browse the repository at this point in the history
* add a preprocessor that casts everything to `str`

* check that integer units are properly converted to `str`

* remove the xfail, this has been fixed 2-3 years ago

* Update cf_xarray/units.py

---------

Co-authored-by: Deepak Cherian <[email protected]>
  • Loading branch information
keewis and dcherian authored Jan 31, 2024
1 parent a9cebee commit 25f5635
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
8 changes: 7 additions & 1 deletion cf_xarray/tests/test_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,13 @@ def test_percent_units():
assert str(ureg("%").units) == "percent"


@pytest.mark.xfail(reason="not supported by pint, yet: hgrecco/pint#1295")
def test_integer_units():
"""Test that integer 1 units is equal to dimensionless"""
# need to explicitly use parse_units to bypass the runtime type checking
# in the quantity constructor
assert str(ureg.parse_units(1)) == "dimensionless"


def test_udunits_power_syntax():
"""Test that UDUNITS style powers are properly parsed and interpreted."""
assert ureg("m2 s-2").units == ureg.m**2 / ureg.s**2
Expand Down
6 changes: 6 additions & 0 deletions cf_xarray/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,13 @@ def repl(m):
],
force_ndarray_like=True,
)
# ----- end block copied from metpy

# need to insert to make sure this is the first preprocessor
# This ensures we convert integer `1` to string `"1"`, as needed by pint.
units.preprocessors.insert(0, str)

# -----
units.define("percent = 0.01 = %")

# Define commonly encountered units (both CF and non-CF) not defined by pint
Expand Down

0 comments on commit 25f5635

Please sign in to comment.