Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion IPython/core/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@

>>> llm_formatter = LLMFormatter(parent=ip.display_formatter)

>>> ip.display_formatter.formatters[LLMFormatter.format_type] = llm_formatter
>>> ip.display_formatter.register_formatter(llm_formatter)

Now any class that define `_repr_llm_` will return a x-vendor/llm as part of
it's display data:
Expand Down Expand Up @@ -146,6 +146,14 @@ def _formatters_default(self):
d[f.format_type] = f
return d

def register_formatter(self, formatter):
if formatter.format_type in self.formatters:
warnings.warn(
f"Replacing formatter {type(self.formatters[formatter.format_type])} with {type(formatter)}",
FormatterWarning,
)
self.formatters[formatter.format_type] = formatter

def format(self, obj, include=None, exclude=None):
"""Return a format data dict for an object.

Expand Down
5 changes: 5 additions & 0 deletions docs/source/whatsnew/pr/formatter-registration.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Formatter registration
======================

Formatter can now be registered in an easier fashion using the new
`DisplayFormatter.register_formatter`method.
19 changes: 19 additions & 0 deletions tests/test_formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@
from IPython import get_ipython
from traitlets.config import Config
from IPython.core.formatters import (
BaseFormatter,
PlainTextFormatter,
HTMLFormatter,
PDFFormatter,
_mod_name_key,
DisplayFormatter,
JSONFormatter,
FormatterWarning,
)
from IPython.utils.io import capture_output

Expand Down Expand Up @@ -608,3 +610,20 @@ class Foo(NamedTuple): ...
f = PlainTextFormatter()
assert f.pprint
assert f(foo) == "Hello World"


def test_formatter_registration():
class TestFormatter(BaseFormatter):
format_type = "x-vendor/test"
print_method = "_repr_test_"
_return_type = (dict, str)

f = get_ipython().display_formatter
formatter = TestFormatter(parent=f)
f.register_formatter(formatter)

assert formatter.format_type in f.formatters

with capture_output() as captured:
with pytest.warns(FormatterWarning):
result = f.register_formatter(formatter)
Loading