Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convention to print an object in python

Is there any standard convention to print an object in python. I know that if I just try to print the object it would print the memory address but I would like to overwrite that method and be able to print human readable format of the object to help in debugging.

is there any standard convention people follow or is it not a good way to define such a method instead there are better alternatives?

like image 842
raju Avatar asked Dec 01 '22 05:12

raju


1 Answers

You can overwrite either the __str__ or the __repr__ method.

There is no convention on how to implement the __str__ method; it can just return any human-readable string representation you want. There is, however, a convention on how to implement the __repr__ method: it should return a string representation of the object so that the object could be recreated from that representation (if possible), i.e. eval(repr(obj)) == obj.

Assuming you have a class Point, __str__ and __repr__ could be implemented like this:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __str__(self):
        return "(%.2f, %.2f)" % (self.x, self.y)
    def __repr__(self):
        return "Point(x=%r, y=%r)" % (self.x, self.y)
    def __eq__(self, other):
        return isinstance(other, Point) and self.x == other.x and self.y == other.y

Example:

>>> p = Point(0.1234, 5.6789)
>>> str(p)
'(0.12, 5.68)'
>>> "The point is %s" % p  # this will call str
'The point is (0.12, 5.68)'
>>> repr(p)
'Point(x=0.1234, y=5.6789)'
>>> p  # echoing p in the interactive shell calls repr internally
Point(x=0.1234, y=5.6789)
>>> eval(repr(p))  # this echos the repr of the new point created by eval
Point(x=0.1234, y=5.6789)
>>> type(eval(repr(p)))
<class '__main__.Point'>
>>> eval(repr(p)) == p
True
like image 141
tobias_k Avatar answered Dec 06 '22 22:12

tobias_k