From 25f5635d8a5abded61c3adefb49a0a2cb824204f Mon Sep 17 00:00:00 2001 From: Justus Magin Date: Wed, 31 Jan 2024 18:00:24 +0100 Subject: [PATCH] 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 --- cf_xarray/tests/test_units.py | 8 +++++++- cf_xarray/units.py | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/cf_xarray/tests/test_units.py b/cf_xarray/tests/test_units.py index fa34b1b2..105fbb25 100644 --- a/cf_xarray/tests/test_units.py +++ b/cf_xarray/tests/test_units.py @@ -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 diff --git a/cf_xarray/units.py b/cf_xarray/units.py index acd48fbe..dea7d6b5 100644 --- a/cf_xarray/units.py +++ b/cf_xarray/units.py @@ -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