IPython _repr_html_

I really like how in IPython Notebook you can add a class method _repr_html_()

to print a rich HTML version of your class.

Is there a way to explicitly force this output to, say, if I want to print two objects at the same time?

print obj1, obj2

      

Below resolved, but I would still like to know if this is possible as writing the wrapper is tedious

Or if I have a wrapper class for many of these objects and I want to nest their HTML view inside the wrapper view?

def _repr_html_(self):
    return '<td>%s</td><td></td>' % (self.obj1, self.obj2)

      

+3


source to share


2 answers


In the second case, you can provide a wrapper object a _repr_html_

that explicitly calls _repr_html_

on its sub-objects and concatenates them in any way you want .

I don't think the first case can be done, because it _repr_html_

is repr

, not, str

and is str

used when you are print

an object. Even if you try to just type obj1, obj2

(without print

), it won't work because it obj1, obj2

is a tuple and the tuple already has its own repr

, which you cannot override (and you can add _html_repr_

to the type of the tuple).

Here's a simple example:



class Foo(object):
    def __init__(self, value):
        self.value = value
    def _repr_html_(self):
        return "<p><em>This is the <strong>{0}</strong> object</em>!</p>".format(self.value)

class Wrapper(object):
    def __init__(self, foo1, foo2):
        self.foo1 = foo1
        self.foo2 = foo2

    def _repr_html_(self):
        return """
        <h3>Foo1</h3>
        {0}
        <h3>Foo2</h3>
        {1}
        """.format(self.foo1._repr_html_(), self.foo2._repr_html_())

      

It will execute with these classes Foo("Blah")

, and create two objects Foo

and end them with Wrapper

. But simply entering foo1, foo2

(where it is a Foo object) won't work for the reason I mentioned above. If you want to HTML render multiple objects, you will have to explicitly wrap them with a wrapper class that has its own _repr_html_

. (Of course, you can give this wrapper class a short name like HTML

or show

or whatever, so you can just do show(obj1, obj2)

.)

0


source


Use from IPython.display import display

and call display

for each or your objects.



+5


source







All Articles