Skip to content

Commit

Permalink
Fix custom formatters needing registry (hgrecco#2011)
Browse files Browse the repository at this point in the history
* Fix custom formatters needing registry

* add a doc note
  • Loading branch information
aulemahal authored Jun 13, 2024
1 parent 5f67733 commit 32ccd20
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 5 deletions.
2 changes: 1 addition & 1 deletion CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Pint Changelog
0.25 (unreleased)
-----------------

Nothing added yet.
- Fix custom formatter needing the registry object. (PR #2011)


0.24 (2024-06-07)
Expand Down
3 changes: 2 additions & 1 deletion docs/user/formatting.rst
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ formats:
'2.3e-06 kilogram ** -1 * meter ** 3 * second ** -2'

where ``unit`` is a :py:class:`dict` subclass containing the unit names and
their exponents.
their exponents, ``registry`` is the current instance of :py:class:``UnitRegistry`` and
``options`` is not yet implemented.

You can choose to replace the complete formatter. Briefly, the formatter if an object with the
following methods: `format_magnitude`, `format_unit`, `format_quantity`, `format_uncertainty`,
Expand Down
2 changes: 2 additions & 0 deletions pint/delegates/formatter/_to_register.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ def wrapper(func: Callable[[PlainUnit, UnitRegistry], str]):
raise ValueError(f"format {name!r} already exists") # or warn instead

class NewFormatter(BaseFormatter):
spec = name

def format_magnitude(
self,
magnitude: Magnitude,
Expand Down
12 changes: 9 additions & 3 deletions pint/delegates/formatter/full.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,17 @@ def get_formatter(self, spec: str):
return v

try:
return REGISTERED_FORMATTERS[spec]
orphan_fmt = REGISTERED_FORMATTERS[spec]
except KeyError:
pass
return self._formatters["D"]

return self._formatters["D"]
try:
fmt = orphan_fmt.__class__(self._registry)
spec = getattr(fmt, "spec", spec)
self._formatters[spec] = fmt
return fmt
except Exception:
return orphan_fmt

def format_magnitude(
self, magnitude: Magnitude, mspec: str = "", **babel_kwds: Unpack[BabelKwds]
Expand Down
2 changes: 2 additions & 0 deletions pint/testsuite/test_formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ def test_split_format(format, default, flag, expected):
def test_register_unit_format(func_registry):
@fmt.register_unit_format("custom")
def format_custom(unit, registry, **options):
# Ensure the registry is correct..
registry.Unit(unit)
return "<formatted unit>"

quantity = 1.0 * func_registry.meter
Expand Down

0 comments on commit 32ccd20

Please sign in to comment.