Skip to content

Commit

Permalink
Adjust format_mass() for pint 0.18
Browse files Browse the repository at this point in the history
pint.formatting.format_unit() changed slightly between pint 0.17 and
0.18; see hgrecco/pint@8c719483, part of hgrecco/pint#1371.

- Discard the "~" format modifier once it has been checked.
- Discard any leading ":".
- Adjust docstring.
  • Loading branch information
khaeru committed Nov 11, 2021
1 parent 7e69589 commit 1bfc651
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions iam_units/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,8 @@ def format_mass(obj, info, spec=None):
info : str
Any information, e.g. the symbol of a GHG species.
spec : str, optional
Pint formatting specifier such as ':H' (HTML format), ':~' (compact
format with symbols), etc.
Pint formatting specifier such as "H" (HTML format), "~C" (compact format with
symbols), etc.
"""
spec = spec or obj.default_format

Expand All @@ -122,15 +122,20 @@ def format_mass(obj, info, spec=None):
except AttributeError:
pass # Already a Unit object

# Use the symbol for a ':~' spec
# Use the symbol if the modifier "~" is in `spec`; else the canonical name. cf.
# pint.Unit.__format__()
method = registry._get_symbol if "~" in spec else lambda k: k
# Collect the pieces of the unit expression
units = [[method(key), value] for key, value in obj._units.items()]

# Index of the mass component
mass_index = list(obj.dimensionality.keys()).index("[mass]")
# Append the information to the mass component
# Append the information (e.g. species) to the mass component
units[mass_index][0] += f" {info}"

# Hand off to pint's formatting
return format_unit(to_units_container(dict(units), registry=registry), spec)
# Prepare pint.util.UnitsContainer and hand off to pint's formatting. Discard "~"
# (used above) and ":" (invalid in pint ≥0.18).
return format_unit(
to_units_container(dict(units), registry=registry),
spec.replace("~", "").lstrip(":"),
)

0 comments on commit 1bfc651

Please sign in to comment.