Implementing __repr__
for a class Foo
with member variables x
and y
, is there a way to automatically populate the string? Example that does not work:
class Foo(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Foo({})".format(**self.__dict__)
>>> foo = Foo(42, 66)
>>> print(foo)
IndexError: tuple index out of range
And another:
from pprint import pprint
class Foo(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Foo({})".format(pprint(self.__dict__))
>>> foo = Foo(42, 66)
>>> print(foo)
{'x': 42, 'y': 66}
Foo(None)
Yes I could define the method as
def __repr__(self):
return "Foo({x={}, y={}})".format(self.x, self.x)
but this gets tedious when there are many member variables.
Python __repr__() function returns the object representation in string format. This method is called when repr() function is invoked on the object. If possible, the string returned should be a valid Python expression that can be used to reconstruct the object again.
repr() compute the “official” string representation of an object (a representation that has all information about the object) and str() is used to compute the “informal” string representation of an object (a representation that is useful for printing the object).
The __repr__ function is defined by the designer of a type, in order to provide a means for users of the type to represent values of that type unambiguously, with a string.
The % symbol is used in Python with a large variety of data types and configurations. %s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string.
I use this as a mixin when I want something like that:
class SimpleRepr(object):
"""A mixin implementing a simple __repr__."""
def __repr__(self):
return "<{klass} @{id:x} {attrs}>".format(
klass=self.__class__.__name__,
id=id(self) & 0xFFFFFF,
attrs=" ".join("{}={!r}".format(k, v) for k, v in self.__dict__.items()),
)
It gives the class name, the (shortened) id, and all of the attributes.
I think you want something like this:
def __repr__(self):
return "Foo({!r})".format(self.__dict__)
This will add repr(self.__dict__)
in the string, using !r
in a format specifier tells format()
to call the item's __repr__()
.
See the "Conversion field" here: https://docs.python.org/3/library/string.html#format-string-syntax
Based on Ned Batchelder's answer, you can replace the line above by
return "{}({!r})".format(self.__class__.__name__, self.__dict__)
for a more generic approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With