Module:core.formatters

Display formatters.

This module defines the base instances in order to implement customformatters/mimetypesgot objects:

As we want to see internal IPython working we are going to use the followingfunction to diaply objects instead of the normal print or display method:

>>>ip=get_ipython()>>>ip.display_formatter.format(...)({'text/plain': 'Ellipsis'}, {})

This return a tuple with the mimebumdle for the current object, and theassociated metadata.

We can now define our own formatter and register it:

>>>fromIPython.core.formattersimportBaseFormatter,FormatterABC
>>>classLLMFormatter(BaseFormatter):......format_type='x-vendor/llm'...print_method='_repr_llm_'..._return_type=(dict,str)
>>>llm_formatter=LLMFormatter(parent=ip.display_formatter)
>>>ip.display_formatter.formatters[LLMFormatter.format_type]=llm_formatter

Now any class that define_repr_llm_ will return a x-vendor/llm as part ofit’s display data:

>>>classA:......def_repr_llm_(self,*kwargs):...return'This a A'...
>>>ip.display_formatter.format(A())({'text/plain': '<IPython.core.formatters.A at ...>', 'x-vendor/llm': 'This a A'}, {})

As usual, you can register methods for third party types (seeFormatters for third-party types)

>>>defllm_int(obj):...return'This is the integer%s, in between%s and%s'%(obj,obj-1,obj+1)
>>>llm_formatter.for_type(int,llm_int)
>>>ip.display_formatter.format(42)({'text/plain': '42', 'x-vendor/llm': 'This is the integer 42, in between 41 and 43'}, {})

Inheritance diagram:

Inheritance diagram of IPython.core.formatters

16 Classes

classIPython.core.formatters.DisplayFormatter(**kwargs:Any)

Bases:Configurable

active_types

List of currently active mime-types to display.You can use this to set a white-list for formats to display.

Most users will not need to change this value.

format(obj,include=None,exclude=None)

Return a format data dict for an object.

By default all format types will be computed.

The following MIME types are usually implemented:

  • text/plain

  • text/html

  • text/markdown

  • text/latex

  • application/json

  • application/javascript

  • application/pdf

  • image/png

  • image/jpeg

  • image/svg+xml

Parameters:
  • obj (object) – The Python object whose format data will be computed.

  • include (list,tuple orset; optional) – A list of format type strings (MIME types) to include in theformat data dict. If this is setonly the format types includedin this list will be computed.

  • exclude (list,tuple orset; optional) – A list of format type string (MIME types) to exclude in the formatdata dict. If this is set all format types will be computed,except for those included in this argument.Mimetypes present in exclude will take precedence over the ones in include

Returns:

(format_dict, metadata_dict) – format_dict is a dictionary of key/value pairs, one of each format that wasgenerated for the object. The keys are the format types, whichwill usually be MIME type strings and the values and JSON’abledata structure containing the raw data for the representation inthat format.

metadata_dict is a dictionary of metadata about each mime-type output.Its keys will be a strict subset of the keys in format_dict.

Return type:

tuple of two dicts

Notes

If an object implement_repr_mimebundle_ as well as various_repr_*_, the data returned by_repr_mimebundle_ will takeprecedence and the corresponding_repr_*_ for this mimetype willnot be called.

propertyformat_types

Return the format types (MIME types) of the active formatters.

classIPython.core.formatters.FormatterWarning

Bases:UserWarning

Warning class for errors in formatters

classIPython.core.formatters.FormatterABC

Bases:object

Abstract base class for Formatters.

A formatter is a callable class that is responsible for computing theraw format data for a particular format type (MIME type). For example,an HTML formatter would have a format type oftext/html and would returnthe HTML representation of the object when called.

classIPython.core.formatters.BaseFormatter(**kwargs:Any)

Bases:Configurable

A base formatter class that is configurable.

This formatter should usually be used as the base class of all formatters.It is a traitedConfigurable class and includes an extensibleAPI for users to determine how their objects are formatted. The followinglogic is used to find a function to format an given object.

  1. The object is introspected to see if it has a method with the nameprint_method. If is does, that object is passed to that methodfor formatting.

  2. If no print method is found, three internal dictionaries are consultedto find print method:singleton_printers,type_printersanddeferred_printers.

Users should use these dictionaries to register functions that will beused to compute the format data for their objects (if those objects don’thave the special print methods). The easiest way of using thesedictionaries is through thefor_type() andfor_type_by_name()methods.

If no function/callable is found to compute the format data,None isreturned and this format type is not used.

for_type(typ,func=None)

Add a format function for a given type.

Parameters:
  • typ (type or'__module__.__name__' string for a type) – The class of the object that will be formatted usingfunc.

  • func (callable) –

    A callable for computing the format data.func will be called with the object to be formatted,and will return the raw data in this formatter’s format.Subclasses may use a different call signature for thefunc argument.

    Iffunc is None or not specified, there will be no change,only returning the current value.

Returns:

oldfunc – The currently registered callable.If you are registering a new formatter,this will be the previous value (to enable restoring later).

Return type:

callable

for_type_by_name(type_module,type_name,func=None)

Add a format function for a type specified by the full dottedmodule and name of the type, rather than the type of the object.

Parameters:
  • type_module (str) – The full dotted name of the module the type is defined in, likenumpy.

  • type_name (str) – The name of the type (the class name), likedtype

  • func (callable) –

    A callable for computing the format data.func will be called with the object to be formatted,and will return the raw data in this formatter’s format.Subclasses may use a different call signature for thefunc argument.

    Iffunc is None or unspecified, there will be no change,only returning the current value.

Returns:

oldfunc – The currently registered callable.If you are registering a new formatter,this will be the previous value (to enable restoring later).

Return type:

callable

lookup(obj)

Look up the formatter for a given instance.

Parameters:

obj (object instance)

Returns:

f – The registered formatting callable for the type.

Return type:

callable

Raises:

KeyError if the type has not been registered.

lookup_by_type(typ)

Look up the registered formatter for a type.

Parameters:

typ (type or'__module__.__name__' string for a type)

Returns:

f – The registered formatting callable for the type.

Return type:

callable

Raises:

KeyError if the type has not been registered.

pop(typ,default=IPython.core.formatters._raise_key_error)

Pop a formatter for the given type.

Parameters:
  • typ (type or'__module__.__name__' string for a type)

  • default (object) – value to be returned if no formatter is registered for typ.

Returns:

obj – The last registered object for the type.

Return type:

object

Raises:

KeyError if the type is not registered and default is not specified.

classIPython.core.formatters.PlainTextFormatter(**kwargs:Any)

Bases:BaseFormatter

The default pretty-printer.

This usesIPython.lib.pretty to compute the format data ofthe object. If the object cannot be pretty printed,repr() is used.See the documentation ofIPython.lib.pretty for details onhow to write pretty printers. Here is a simple example:

defdtype_pprinter(obj,p,cycle):ifcycle:returnp.text('dtype(...)')ifhasattr(obj,'fields'):ifobj.fieldsisNone:p.text(repr(obj))else:p.begin_group(7,'dtype([')fori,fieldinenumerate(obj.descr):ifi>0:p.text(',')p.breakable()p.pretty(field)p.end_group(7,'])')
max_seq_length

Truncate large collections (lists, dicts, tuples, sets) to this size.

Set to 0 to disable truncation.

classIPython.core.formatters.HTMLFormatter(**kwargs:Any)

Bases:BaseFormatter

An HTML formatter.

To define the callables that compute the HTML representation of yourobjects, define a_repr_html_() method or use thefor_type()orfor_type_by_name() methods to register functions that handlethis.

The return value of this formatter should be a valid HTML snippet thatcould be injected into an existing DOM. It shouldnot include the`<html> or`<body> tags.

classIPython.core.formatters.MarkdownFormatter(**kwargs:Any)

Bases:BaseFormatter

A Markdown formatter.

To define the callables that compute the Markdown representation of yourobjects, define a_repr_markdown_() method or use thefor_type()orfor_type_by_name() methods to register functions that handlethis.

The return value of this formatter should be a valid Markdown.

classIPython.core.formatters.SVGFormatter(**kwargs:Any)

Bases:BaseFormatter

An SVG formatter.

To define the callables that compute the SVG representation of yourobjects, define a_repr_svg_() method or use thefor_type()orfor_type_by_name() methods to register functions that handlethis.

The return value of this formatter should be valid SVG enclosed in`<svg>` tags, that could be injected into an existing DOM. It shouldnot include the`<html> or`<body> tags.

classIPython.core.formatters.PNGFormatter(**kwargs:Any)

Bases:BaseFormatter

A PNG formatter.

To define the callables that compute the PNG representation of yourobjects, define a_repr_png_() method or use thefor_type()orfor_type_by_name() methods to register functions that handlethis.

The return value of this formatter should be raw PNG data,notbase64 encoded.

classIPython.core.formatters.JPEGFormatter(**kwargs:Any)

Bases:BaseFormatter

A JPEG formatter.

To define the callables that compute the JPEG representation of yourobjects, define a_repr_jpeg_() method or use thefor_type()orfor_type_by_name() methods to register functions that handlethis.

The return value of this formatter should be raw JPEG data,notbase64 encoded.

classIPython.core.formatters.LatexFormatter(**kwargs:Any)

Bases:BaseFormatter

A LaTeX formatter.

To define the callables that compute the LaTeX representation of yourobjects, define a_repr_latex_() method or use thefor_type()orfor_type_by_name() methods to register functions that handlethis.

The return value of this formatter should be a valid LaTeX equation,enclosed in either`$`,`$$` or another LaTeX equationenvironment.

classIPython.core.formatters.JSONFormatter(**kwargs:Any)

Bases:BaseFormatter

A JSON string formatter.

To define the callables that compute the JSONable representation ofyour objects, define a_repr_json_() method or use thefor_type()orfor_type_by_name() methods to register functions that handlethis.

The return value of this formatter should be a JSONable list or dict.JSON scalars (None, number, string) are not allowed, only dict or list containers.

classIPython.core.formatters.JavascriptFormatter(**kwargs:Any)

Bases:BaseFormatter

A Javascript formatter.

To define the callables that compute the Javascript representation ofyour objects, define a_repr_javascript_() method or use thefor_type() orfor_type_by_name() methods to register functionsthat handle this.

The return value of this formatter should be valid Javascript code andshouldnot be enclosed in`<script>` tags.

classIPython.core.formatters.PDFFormatter(**kwargs:Any)

Bases:BaseFormatter

A PDF formatter.

To define the callables that compute the PDF representation of yourobjects, define a_repr_pdf_() method or use thefor_type()orfor_type_by_name() methods to register functions that handlethis.

The return value of this formatter should be raw PDF data,notbase64 encoded.

classIPython.core.formatters.IPythonDisplayFormatter(**kwargs:Any)

Bases:BaseFormatter

An escape-hatch Formatter for objects that know how to display themselves.

To define the callables that compute the representation of yourobjects, define a_ipython_display_() method or use thefor_type()orfor_type_by_name() methods to register functions that handlethis. Unlike mime-type displays, this method should not return anything,instead calling any appropriate display methods itself.

This display formatter has highest priority.If it fires, no other display formatter will be called.

Prior to IPython 6.1,_ipython_display_ was the only way to display custom mime-typeswithout registering a new Formatter.

IPython 6.1 introduces_repr_mimebundle_ for displaying custom mime-types,so_ipython_display_ should only be used for objects that require unusualdisplay patterns, such as multiple display calls.

classIPython.core.formatters.MimeBundleFormatter(**kwargs:Any)

Bases:BaseFormatter

A Formatter for arbitrary mime-types.

Unlike other_repr_<mimetype>_ methods,_repr_mimebundle_ should return mime-bundle data,either the mime-keyeddata dictionary or the tuple(data,metadata).Any mime-type is valid.

To define the callables that compute the mime-bundle representation of yourobjects, define a_repr_mimebundle_() method or use thefor_type()orfor_type_by_name() methods to register functions that handlethis.

Added in version 6.1.

2 Functions

IPython.core.formatters.catch_format_error(method,self)

show traceback on failed format call

IPython.core.formatters.format_display_data(obj,include=None,exclude=None)

Return a format data dict for an object.

By default all format types will be computed.

Parameters:

obj (object) – The Python object whose format data will be computed.

Returns:

  • format_dict (dict) – A dictionary of key/value pairs, one or each format that wasgenerated for the object. The keys are the format types, whichwill usually be MIME type strings and the values and JSON’abledata structure containing the raw data for the representation inthat format.

  • include (list or tuple, optional) – A list of format type strings (MIME types) to include in theformat data dict. If this is setonly the format types includedin this list will be computed.

  • exclude (list or tuple, optional) – A list of format type string (MIME types) to exclude in the formatdata dict. If this is set all format types will be computed,except for those included in this argument.