dvreed77
dvreed77

Reputation: 2387

IPython _repr_html_

I really like how in the IPython Notebook you can add a class method called _repr_html_() to print a rich HTML version of your class.

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

print obj1, obj2

Below is solved, but I would still like to know if the above is possible since writing a wrapper is tad tedious

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

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

Upvotes: 5

Views: 13531

Answers (2)

Matt
Matt

Reputation: 27843

Use from IPython.display import display and call display on each or your objects.

Upvotes: 11

BrenBarn
BrenBarn

Reputation: 251548

For the second case, you can give the wrapper object a _repr_html_ that explicitly calls _repr_html_ on its sub-objects and combines them in whatever way you like.

I don't think it's possible to make the first case work, because _repr_html_ is a repr, not a str and str is used when you print an object. Even if you try to just enter obj1, obj2 (without the print), it won't work, because obj1, obj2 is a tuple, and a tuple already has its own repr that you can't override (nor can you add an _html_repr_ to the tuple type).

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_())

With these classes, doing Foo("Blah") will work, and creating two Foo objects and wrapping them with a Wrapper will work. But just entering foo1, foo2 (where those are Foo object) won't work, for the reason I described above. If you want to HTML-display multiple objects, you'll have to explicitly wrap them with a wrapper class that has its own _repr_html_. (Of course, you could give this wrapper class a short name like HTML or show or whatever, so you can just do show(obj1, obj2).)

Upvotes: 2

Related Questions