Skip to content

Commit

Permalink
Fix unit power regex for parentheses handling
Browse files Browse the repository at this point in the history
  • Loading branch information
jthielen committed Mar 7, 2022
1 parent 28db568 commit 233d7ca
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/metpy/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
preprocessors=[
functools.partial(
re.sub,
r'(?<=[A-Za-z])(?![A-Za-z])(?<![0-9\-][eE])(?<![0-9\-])(?=[0-9\-])',
r'(?<=[A-Za-z\)])(?![A-Za-z\)])(?<![0-9\-][eE])(?<![0-9\-])(?=[0-9\-])',
'**'
),
lambda string: string.replace('%', 'percent')
Expand Down
22 changes: 20 additions & 2 deletions tests/units/test_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,24 @@ def test_percent_units():
assert str(units('%').units) == 'percent'


def test_udunits_power_syntax():
@pytest.mark.parametrize(
'unit_str,pint_unit',
(
# Validated against cf-units (UDUNITS-2 wrapper)
('m s-1', units.m / units.s),
('m2 s-2', units.m ** 2 / units.s ** 2),
('kg(-1)', units.kg),
('kg-1', units.kg ** -1),
('W m(-2)', units.m ** 3 * units.kg * units.s ** -3),
('W m-2', units.kg * units.s ** -3),
('(W m-2 um-1)-1', units.m * units.kg ** -1 * units.s ** 3),
pytest.param(
'(J kg-1)(m s-1)-1', units.m / units.s,
marks=pytest.mark.xfail(reason="hgrecco/pint#1485")
),
('(J kg-1)(m s-1)(-1)', units.m ** 3 / units.s ** 3)
)
)
def test_udunits_power_syntax(unit_str, pint_unit):
"""Test that UDUNITS style powers are properly parsed and interpreted."""
assert units('m2 s-2').units == units.m ** 2 / units.s ** 2
assert units(unit_str).to_base_units().units == pint_unit

0 comments on commit 233d7ca

Please sign in to comment.