Skip to content

Instantly share code, notes, and snippets.

@njsmith
Created July 14, 2012 20:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save njsmith/3113186 to your computer and use it in GitHub Desktop.
Save njsmith/3113186 to your computer and use it in GitHub Desktop.
Convenience function for implementing _repr_pretty_
# It's very common for a class to have a repr that looks like MyClass(a, b, c=d).
# But the IPython pretty-printing machinery doesn't make this very convenient.
# Here's a helper to make it convenient.
def pretty_constructor_call(p, obj, args, kwargs=[]):
name = obj.__class__.__name__
p.begin_group(len(name) + 1, "%s(" % (name,))
started = [False]
def new_item():
if started[0]:
p.text(",")
p.breakable()
started[0] = True
for arg in args:
new_item()
p.pretty(arg)
for label, value in kwargs:
new_item()
p.begin_group(len(label) + 1, "%s=" % (label,))
p.pretty(value)
p.end_group(len(label) + 1, "")
p.end_group(len(name) + 1, ")")
# Usage example:
class MyClass(object):
def __init__(self, a, b, c=None):
self.a = a
self.b = b
self.c = c
def _repr_pretty_(self, p, cycle):
assert not cycle
kwargs = []
if self.c is not None:
kwargs.append(("c", c))
pretty_constructor_call(p, self, [self.a, self.b], kwargs)
# Why is this useful? Here's some parse tree objects that use the above function:
# In [21]: patsy.parse_formula.parse_formula("y ~ a + b")
# Out[21]:
# ParseNode('~',
# Token('~', <Origin y ->~<- a + b (2-3)>),
# [ParseNode('PYTHON_EXPR',
# Token('PYTHON_EXPR',
# <Origin ->y<- ~ a + b (0-1)>,
# extra='y'),
# []),
# ParseNode('+',
# Token('+', <Origin y ~ a ->+<- b (6-7)>),
# [ParseNode('PYTHON_EXPR',
# Token('PYTHON_EXPR',
# <Origin y ~ ->a<- + b (4-5)>,
# extra='a'),
# []),
# ParseNode('PYTHON_EXPR',
# Token('PYTHON_EXPR',
# <Origin y ~ a + ->b<- (8-9)>,
# extra='b'),
# [])])])
#
# Try doing that with ordinary __repr__!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment