Skip to content

Commit

Permalink
Merge pull request #1281 from jthielen/pint-unit-preprocessor
Browse files Browse the repository at this point in the history
Add percent sign and UDUNITS exponent syntax support via Pint's new preprocessor option
  • Loading branch information
dopplershift authored Jan 10, 2020
2 parents 998918d + 51de8ce commit 34fab83
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/metpy/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import functools
from inspect import Parameter, signature
import logging
import re
import warnings

import numpy as np
Expand All @@ -27,7 +28,17 @@
UndefinedUnitError = pint.UndefinedUnitError
DimensionalityError = pint.DimensionalityError

units = pint.UnitRegistry(autoconvert_offset_to_baseunit=True)
# Create registry, with preprocessors for UDUNITS-style powers (m2 s-2) and percent signs
try:
units = pint.UnitRegistry(autoconvert_offset_to_baseunit=True,
preprocessors=[functools.partial(
re.sub,
(r'(?<=[A-Za-z])(?![A-Za-z])(?<![0-9\-][eE])'
r'(?<![0-9\-])(?=[0-9\-])'),
'**'),
lambda string: string.replace('%', 'percent')])
except TypeError:
units = pint.UnitRegistry(autoconvert_offset_to_baseunit=True)

# Capture v0.10 NEP 18 warning on first creation
with warnings.catch_warnings():
Expand Down
15 changes: 15 additions & 0 deletions tests/units/test_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# SPDX-License-Identifier: BSD-3-Clause
r"""Tests the operation of MetPy's unit support code."""

from distutils.version import LooseVersion
import sys

import matplotlib.pyplot as plt
Expand Down Expand Up @@ -217,3 +218,17 @@ def test_assert_nan_checks_units():
"""Test that assert_nan properly checks units."""
with pytest.raises(AssertionError):
assert_nan(np.nan * units.m, units.second)


@pytest.mark.skipif(LooseVersion(pint.__version__) < LooseVersion('0.10'),
reason='Custom preprocessors only available in Pint 0.10')
def test_percent_units():
"""Test that percent sign units are properly parsed and interpreted."""
assert str(units('%').units) == 'percent'


@pytest.mark.skipif(LooseVersion(pint.__version__) < LooseVersion('0.10'),
reason='Custom preprocessors only available in Pint 0.10')
def test_udunits_power_syntax():
"""Test that UDUNITS style powers are properly parsed and interpreted."""
assert units('m2 s-2').units == units.m ** 2 / units.s ** 2

0 comments on commit 34fab83

Please sign in to comment.