Skip to content

__repr__ Does not honor subclasses #261

@darricktheprogrammer

Description

@darricktheprogrammer

A common pattern for me is to subclass Box to get all of its features, but with a type custom to the application. Because box hard codes the types in the __repr__ method for each class, failed test reports and print debugging is often confusing. Where I am expecting to see MyCustomBox(...), instead just Box(...) is printed which makes me think I incorrectly instantiated an object.

This can be fixed by using type(self).__name__ instead of hard coding each type name within the class. It also has the benefit that duplicate code could be removed from some builtin Box subclasses, such as SBox because it would be dynamically generated from the base Box class.

Example:

from box import Box


class MyBox(Box):
    pass


class ActuallyMyBox(Box):
    def __repr__(self):
        return f"{type(self).__name__}({self})"


b1 = MyBox(a=1)
b2 = ActuallyMyBox(b=2)
print(repr(b1))
print(repr(b2))

>>> Box({'a': 1})
>>> ActuallyMyBox({'b': 2})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions