Skip to content

Notebook calls both __repr__ and _repr_html_ #9771

@EntilZha

Description

@EntilZha

Observed Behavior:

  1. Define _repr_html_ on class
  2. In Jupyter/IPython notebook create an instance of the class
  3. Showing the variable by it being the last line in a cell calls both __repr__ and _repr_html_

Expected Behavior:

Jupyter/IPython notebook should call only _repr_html_ if it is defined.

Rationale:

  1. The return of repr is never shown to the user so there is no need to call it if _repr_html_ is defined already.
  2. For object's whose repr function is expensive to call (eg large collections), _repr_html_ can be implemented efficiently by only showing a subset of the collection. This is allowed since although repr in general should adhere to its output being runnable by eval, _repr_html_ does not have to adhere to this since it produces HTML.

Minimal Example

class Custom:
    def __repr__(self):
        raise Exception("oops called repr")

    def _repr_html_(self):
        return "<h1>HTML repr</h1>"

In jupyter cell:

a = Custom()
a

This results in: https://gist.github.com/EntilZha/6b81fc9ced2540a5b7acdebc37c66346

Note, the HTML output is still printed despite the exception.

System Information

  • Mac OS X 10.11.5
  • Safari 9
  • IPython 5.0.0
  • Jupyter 1.0.0
  • Python 3 via brew

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions