Skip to content

Infinite recursion when repr'ing Exception types #224

@apmorton

Description

@apmorton

class ApprovalException(Exception):
def __init__(self, value: str) -> None:
super().__init__(self)
self.value = value
@override
def __str__(self) -> str:
return self.value

>>> repr(approvaltests.ApprovalException('hello'))

RecursionError                            Traceback (most recent call last)
Cell In[4], line 1
----> 1 repr(approvaltests.ApprovalException('hello'))

RecursionError: maximum recursion depth exceeded while getting the repr of an object

ReporterMissingException also suffers from this.

https://github.com/search?q=repo%3Aapprovals%2FApprovalTests.Python%20super().__init__(self)&type=code

The pythonic way to write exceptions like this would be:

class MyException(Exception):
    pass

You can then format the message at the raise-site, or use a static-method.

If you override the constructor signature of an exception you also need to worry about implementing __reduce__ correctly, as the built-in default for Exception will very likely be incorrect.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions