[New-bugs-announce] [issue42259] pprint: infinite recursion for saferepr() when using nested objects, but str() works

Danylo Hlynskyi report at bugs.python.org
Wed Nov 4 06:44:31 EST 2020


New submission from Danylo Hlynskyi <abcz2.uprola at gmail.com>:

First, here's an example using str():

```
class NiceObject:
    def __str__(self):
        return str(self.__dict__)
    def __repr__(self):
        return str(self)

s = NiceObject()
s.self = s
```
This outputs:
```
>>> s
{'self': {...}}
```

When I replace str() call with pprint.saferepr(), I end up in infinite recursion.
```
import pprint

class ReallyNiceObject:
    def __str__(self):
        return pprint.saferepr(self.__dict__)
    def __repr__(self):
        return str(self)
```

Same happens for pprint.pformat(), with depth set.

Is this expected behavior?

----------
components: Library (Lib)
messages: 380315
nosy: danbst
priority: normal
severity: normal
status: open
title: pprint: infinite recursion for saferepr() when using nested objects, but str() works
type: behavior
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42259>
_______________________________________


More information about the New-bugs-announce mailing list