Skip to content

Commit

Permalink
refactor: simplify register_unit_format to avoid in function imports …
Browse files Browse the repository at this point in the history
…and better interplay with registry
  • Loading branch information
hgrecco committed Jan 20, 2024
1 parent 3421f24 commit bc32ac1
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 38 deletions.
23 changes: 5 additions & 18 deletions pint/delegates/formatter/_spec_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
_PRETTY_EXPONENTS = "⁰¹²³⁴⁵⁶⁷⁸⁹"
_JOIN_REG_EXP = re.compile(r"{\d*}")

REGISTERED_FORMATTERS: dict[str, Any] = {}


def parse_spec(spec: str) -> str:
"""Parse and return spec.
Expand All @@ -39,16 +41,12 @@ def parse_spec(spec: str) -> str:
- what happens if two distinct values are found?
"""
# TODO: provisional
from ...formatting import _ORPHAN_FORMATTER

_FORMATTERS = _ORPHAN_FORMATTER._formatters

result = ""
for ch in reversed(spec):
if ch == "~" or ch in _BASIC_TYPES:
continue
elif ch in list(_FORMATTERS.keys()) + ["~"]:
elif ch in list(REGISTERED_FORMATTERS.keys()) + ["~"]:
if result:
raise ValueError("expected ':' after format specifier")
else:
Expand Down Expand Up @@ -93,18 +91,12 @@ def extract_custom_flags(spec: str) -> str:
(i.e those not part of Python's formatting mini language)
"""
import re

if not spec:
return ""

# TODO: provisional
from ...formatting import _ORPHAN_FORMATTER

_FORMATTERS = _ORPHAN_FORMATTER._formatters

# sort by length, with longer items first
known_flags = sorted(_FORMATTERS.keys(), key=len, reverse=True)
known_flags = sorted(REGISTERED_FORMATTERS.keys(), key=len, reverse=True)

flag_re = re.compile("(" + "|".join(known_flags + ["~"]) + ")")
custom_flags = flag_re.findall(spec)
Expand All @@ -118,12 +110,7 @@ def remove_custom_flags(spec: str) -> str:
(i.e those not part of Python's formatting mini language)
"""

# TODO: provisional
from ...formatting import _ORPHAN_FORMATTER

_FORMATTERS = _ORPHAN_FORMATTER._formatters

for flag in sorted(_FORMATTERS.keys(), key=len, reverse=True) + ["~"]:
for flag in sorted(REGISTERED_FORMATTERS.keys(), key=len, reverse=True) + ["~"]:
if flag:
spec = spec.replace(flag, "")
return spec
Expand Down
11 changes: 3 additions & 8 deletions pint/delegates/formatter/_to_register.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@

from typing import TYPE_CHECKING, Callable
from ...compat import ndarray, np, Unpack
from ._spec_helpers import (
split_format,
join_mu,
)
from ._spec_helpers import split_format, join_mu, REGISTERED_FORMATTERS

from ..._typing import Magnitude

Expand Down Expand Up @@ -55,11 +52,9 @@ def format_custom(unit, registry, **options):
f"{u:custom}"
"""

from ...formatting import _ORPHAN_FORMATTER

# TODO: kwargs missing in typing
def wrapper(func: Callable[[PlainUnit, UnitRegistry], str]):
if name in _ORPHAN_FORMATTER._formatters:
if name in REGISTERED_FORMATTERS:
raise ValueError(f"format {name!r} already exists") # or warn instead

class NewFormatter:
Expand Down Expand Up @@ -112,6 +107,6 @@ def format_quantity(
self.format_unit(quantity.units, uspec, **babel_kwds),
)

_ORPHAN_FORMATTER._formatters[name] = NewFormatter()
REGISTERED_FORMATTERS[name] = NewFormatter()

return wrapper
17 changes: 14 additions & 3 deletions pint/delegates/formatter/full.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from .latex import LatexFormatter, SIunitxFormatter
from .plain import RawFormatter, CompactFormatter, PrettyFormatter, DefaultFormatter
from ._format_helpers import BabelKwds
from ._to_register import REGISTERED_FORMATTERS

if TYPE_CHECKING:
from ...facets.plain import PlainQuantity, PlainUnit, MagnitudeT
Expand Down Expand Up @@ -75,10 +76,8 @@ def get_formatter(self, spec: str):
if k in spec:
return v

from ...formatting import _ORPHAN_FORMATTER

try:
return _ORPHAN_FORMATTER._formatters[spec]
return REGISTERED_FORMATTERS[spec]
except KeyError:
pass

Expand Down Expand Up @@ -200,3 +199,15 @@ def format_quantity_babel(
length=length or self.babel_length,
locale=locale or self.locale,
)


################################################################
# This allows to format units independently of the registry
#
REGISTERED_FORMATTERS["raw"] = RawFormatter()
REGISTERED_FORMATTERS["D"] = DefaultFormatter()
REGISTERED_FORMATTERS["H"] = HTMLFormatter()
REGISTERED_FORMATTERS["P"] = PrettyFormatter()
REGISTERED_FORMATTERS["Lx"] = SIunitxFormatter()
REGISTERED_FORMATTERS["L"] = LatexFormatter()
REGISTERED_FORMATTERS["C"] = CompactFormatter()
9 changes: 2 additions & 7 deletions pint/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@


# Backwards compatiblity stuff
from .delegates.formatter import Formatter
from .delegates.formatter.latex import (
vector_to_latex, # noqa
matrix_to_latex, # noqa
Expand All @@ -33,15 +32,11 @@
extract_custom_flags, # noqa
remove_custom_flags, # noqa
split_format, # noqa
REGISTERED_FORMATTERS,
) # noqa
from .delegates.formatter._to_register import register_unit_format # noqa


# TODO: This will be gone soon.

_ORPHAN_FORMATTER = Formatter()


def format_unit(unit, spec: str, registry=None, **options):
# registry may be None to allow formatting `UnitsContainer` objects
# in that case, the spec may not be "Lx"
Expand All @@ -56,7 +51,7 @@ def format_unit(unit, spec: str, registry=None, **options):
spec = "D"

if registry is None:
_formatter = _ORPHAN_FORMATTER._formatters.get(spec, None)
_formatter = REGISTERED_FORMATTERS.get(spec, None)
else:
try:
_formatter = registry._formatters[spec]
Expand Down
5 changes: 3 additions & 2 deletions pint/testsuite/test_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@ def test_unit_formatting_snake_case(self, subtests):
assert f"{x}" == result, f"Failed for {spec}, {result}"

def test_unit_formatting_custom(self, monkeypatch):
from pint import formatting, register_unit_format
from pint import register_unit_format
from pint.delegates.formatter._spec_helpers import REGISTERED_FORMATTERS

@register_unit_format("new")
def format_new(unit, *args, **options):
Expand All @@ -148,7 +149,7 @@ def format_new(unit, *args, **options):

assert f"{ureg.m:new}" == "new format"

del formatting._ORPHAN_FORMATTER._formatters["new"]
del REGISTERED_FORMATTERS["new"]

def test_ipython(self):
alltext = []
Expand Down

0 comments on commit bc32ac1

Please sign in to comment.