Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python __repr__ for all member variables

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.

like image 513
BoltzmannBrain Avatar asked Jun 16 '17 17:06

BoltzmannBrain


People also ask

What is the use of __ repr __ in Python?

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.

What does the repr () function do?

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).

What is __ repr __ Sqlalchemy?

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.

What does %s mean in Python?

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.


2 Answers

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.

like image 65
Ned Batchelder Avatar answered Oct 02 '22 10:10

Ned Batchelder


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.

like image 32
Nathan.Eilisha Shiraini Avatar answered Oct 02 '22 10:10

Nathan.Eilisha Shiraini