Skip to content

Commit 32ccd20

Browse files
authored
Fix custom formatters needing registry (#2011)
* Fix custom formatters needing registry * add a doc note
1 parent 5f67733 commit 32ccd20

File tree

5 files changed

+16
-5
lines changed

5 files changed

+16
-5
lines changed

CHANGES

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ Pint Changelog
44
0.25 (unreleased)
55
-----------------
66

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

99

1010
0.24 (2024-06-07)

docs/user/formatting.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,8 @@ formats:
9898
'2.3e-06 kilogram ** -1 * meter ** 3 * second ** -2'
9999

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

103104
You can choose to replace the complete formatter. Briefly, the formatter if an object with the
104105
following methods: `format_magnitude`, `format_unit`, `format_quantity`, `format_uncertainty`,

pint/delegates/formatter/_to_register.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ def wrapper(func: Callable[[PlainUnit, UnitRegistry], str]):
6161
raise ValueError(f"format {name!r} already exists") # or warn instead
6262

6363
class NewFormatter(BaseFormatter):
64+
spec = name
65+
6466
def format_magnitude(
6567
self,
6668
magnitude: Magnitude,

pint/delegates/formatter/full.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,11 +103,17 @@ def get_formatter(self, spec: str):
103103
return v
104104

105105
try:
106-
return REGISTERED_FORMATTERS[spec]
106+
orphan_fmt = REGISTERED_FORMATTERS[spec]
107107
except KeyError:
108-
pass
108+
return self._formatters["D"]
109109

110-
return self._formatters["D"]
110+
try:
111+
fmt = orphan_fmt.__class__(self._registry)
112+
spec = getattr(fmt, "spec", spec)
113+
self._formatters[spec] = fmt
114+
return fmt
115+
except Exception:
116+
return orphan_fmt
111117

112118
def format_magnitude(
113119
self, magnitude: Magnitude, mspec: str = "", **babel_kwds: Unpack[BabelKwds]

pint/testsuite/test_formatting.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ def test_split_format(format, default, flag, expected):
5959
def test_register_unit_format(func_registry):
6060
@fmt.register_unit_format("custom")
6161
def format_custom(unit, registry, **options):
62+
# Ensure the registry is correct..
63+
registry.Unit(unit)
6264
return "<formatted unit>"
6365

6466
quantity = 1.0 * func_registry.meter

0 commit comments

Comments
 (0)