Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

__repr__ Does not honor subclasses #261

Open
darricktheprogrammer opened this issue Oct 15, 2023 · 0 comments
Open

__repr__ Does not honor subclasses #261

darricktheprogrammer opened this issue Oct 15, 2023 · 0 comments

Comments

@darricktheprogrammer
Copy link

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})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant