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

Closed
darricktheprogrammer opened this issue Oct 15, 2023 · 1 comment
Closed

__repr__ Does not honor subclasses #261

darricktheprogrammer opened this issue Oct 15, 2023 · 1 comment

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})
cdgriffith added a commit that referenced this issue Jun 12, 2024
* Adding #266 support for accessing nested items in BoxList using numpy-style tuple indexing (thanks to Bit0r)
* Adding tests and Cython releases for Python 3.12
* Fixing #251 support for circular references in lists (thanks to Muspi Merol)
* Fixing #261 altering all `__repr__` methods so that subclassing will output the correct class name (thanks to Gabriel Tkacz)
* Fixing #267 Fix type 'int' not iterable (thanks to YISH)

---------

Co-authored-by: Bit0r <nie_wang@outlook.com>
Co-authored-by: Muspi Merol <me@promplate.dev>
Co-authored-by: Gabriel Tkacz <55806524+gtkacz@users.noreply.github.com>
Co-authored-by: Gabriel Tkacz <gabriel.tkacz@gscap.com.br>
Co-authored-by: YISH <mokeyish@hotmail.com>
@cdgriffith
Copy link
Owner

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

2 participants