Skip to content

Commit 25f5635

Browse files
keewisdcherian
andauthored
cast units to str before applying any other preprocessor (#498)
* 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]>
1 parent a9cebee commit 25f5635

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

cf_xarray/tests/test_units.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,13 @@ def test_percent_units():
5151
assert str(ureg("%").units) == "percent"
5252

5353

54-
@pytest.mark.xfail(reason="not supported by pint, yet: hgrecco/pint#1295")
54+
def test_integer_units():
55+
"""Test that integer 1 units is equal to dimensionless"""
56+
# need to explicitly use parse_units to bypass the runtime type checking
57+
# in the quantity constructor
58+
assert str(ureg.parse_units(1)) == "dimensionless"
59+
60+
5561
def test_udunits_power_syntax():
5662
"""Test that UDUNITS style powers are properly parsed and interpreted."""
5763
assert ureg("m2 s-2").units == ureg.m**2 / ureg.s**2

cf_xarray/units.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,13 @@ def repl(m):
7777
],
7878
force_ndarray_like=True,
7979
)
80+
# ----- end block copied from metpy
81+
82+
# need to insert to make sure this is the first preprocessor
83+
# This ensures we convert integer `1` to string `"1"`, as needed by pint.
84+
units.preprocessors.insert(0, str)
8085

86+
# -----
8187
units.define("percent = 0.01 = %")
8288

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

0 commit comments

Comments
 (0)