Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling print(self) under __str__ throws a RecursionError

I have defined a class called spam:

class spam():
    def __str__(self):
        print(self)
a = spam()

print(a)

The print statement in the end gives me the following error:

    Traceback (most recent call last):
  File "<pyshell#73>", line 1, in <module>
    print(a)
  File "<pyshell#51>", line 3, in __str__
    print(self)
  File "<pyshell#51>", line 3, in __str__
    print(self)
  File "<pyshell#51>", line 3, in __str__
    print(self)
  #same lines repeated several times
  RecursionError: maximum recursion depth exceeded

What is going on here? What happens when I say print(self) under str(self)? What is causing the recursion?

like image 637
Aman Vernekar Avatar asked Dec 30 '25 03:12

Aman Vernekar


1 Answers

print calls str on the non-string object to be able to print it, which calls your __str__ member method.

Here is your recursion.

You define a __str__ method when you are able to convert your object to an "equivalent" string. If not, just leave the default (which prints the object type & address)

Note that __str__ should return something, not print. If you have some representative attribute, you could use it to return something interesting.

class spam():
    def __init__(self,value):
        self.__value = value
    def __str__(self):
        return "object '{}' with value {}".format(self.__class__.__name__, self.__value)

a = spam(10)
print(a)

prints:

object 'spam' with value 10
like image 90
Jean-François Fabre Avatar answered Jan 01 '26 20:01

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!