[Tutor] __repr__ and __str__

Marilyn Davis marilyn at pythontrainer.com
Tue Jun 30 08:47:45 CEST 2015


Hello Python Tutors,

A student has asked a question that has me stumped.  We are using 2.7.

Looking at this code:

#!/usr/bin/python

class MyList(list):

    def __str__(self):
        return """Here are your data:
    %s
    """ % list.__str__(self)

def main():
    a = MyList([1,2])
    print a

if __name__ == "__main__":
    main()

___

We get the expected output:

Here are your data:
    [1, 2]

But if we add the special method:

    def __repr__(self):
        return "MyList(%s)" % (list.__str__(self))

we get:

Traceback (most recent call last):
  File "./stack2.py", line 17, in <module>
    main()
  File "./stack2.py", line 14, in main
    print a
  File "./stack2.py", line 10, in __str__
    """ % list.__str__(self)
  File "./stack2.py", line 5, in __repr__
    return "MyList(%s)" % (list.__str__(self))
  File "./stack2.py", line 5, in __repr__
    return "MyList(%s)" % (list.__str__(self))

and on and on to the:

RuntimeError: maximum recursion depth exceeded

--

>From https://docs.python.org/2/reference/datamodel.html:

If a class defines __repr__() but not __str__(), then __repr__() is also
used when an “informal” string representation of instances of that class
is required.

__

So ?????  __str__ is defined and works just fine unless we also define
__repr__.

What am I missing?

Thank you for any help.

Marilyn Davis



More information about the Tutor mailing list