Best output type and encoding practices for __repr__() functions?

In Python2, __repr__ (and __str__) must return a string object, not a unicode object. In Python3, the situation is reversed, __repr__ and __str__ must return unicode objects, not byte (née string) objects: class Foo(object): def __repr__(self): return u’\N{WHITE SMILING FACE}’ class Bar(object): def __repr__(self): return u’\N{WHITE SMILING FACE}’.encode(‘utf8’) repr(Bar()) # ☺ repr(Foo()) # UnicodeEncodeError: ‘ascii’ …

Read more

What is the meaning of %r?

Background: In Python, there are two builtin functions for turning an object into a string: str vs. repr. str is supposed to be a friendly, human readable string. repr is supposed to include detailed information about an object’s contents (sometimes, they’ll return the same thing, such as for integers). By convention, if there’s a Python …

Read more

Understanding repr( ) function in Python

>>> x = ‘foo’ >>> x ‘foo’ So the name x is attached to ‘foo’ string. When you call for example repr(x) the interpreter puts ‘foo’ instead of x and then calls repr(‘foo’). >>> repr(x) “‘foo'” >>> x.__repr__() “‘foo'” repr actually calls a magic method __repr__ of x, which gives the string containing the representation …

Read more

What is the difference between __str__ and __repr__?

Alex summarized well but, surprisingly, was too succinct. First, let me reiterate the main points in Alex’s post: The default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah) __repr__ goal is to be unambiguous __str__ goal is to be readable Container’s __str__ uses contained objects’ __repr__ Default implementation is …

Read more