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

ENH: avoid subclassing builtin dict #4116

Merged
merged 1 commit into from
Sep 12, 2022

Conversation

neutrinoceros
Copy link
Member

PR Summary

problem

Subclassing builtin types like dict is error prone because overriden methods are mostly ignored.
This can lead to very subtle bugs where custom classes don't behave as one would expect

class DoubleDict(dict):
    def __setitem__(self, key, value):
        return super().__setitem__(key, [value] * 2)

d = DoubleDict(a=1)
d["b"] = 2
print(d)

outputs

{'a': 1, 'b': [2, 2]}

We see that the user-defined __setitem__ method is correctly used when setting a new value, but is ignored at initialization.

solution

subclass collections.UserDict instead, which is intended to avoid these subtle issues

@neutrinoceros neutrinoceros added the enhancement Making something better label Sep 10, 2022
@neutrinoceros neutrinoceros marked this pull request as ready for review September 10, 2022 18:15
Copy link
Member

@matthewturk matthewturk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems fine

@matthewturk matthewturk merged commit e65a10f into yt-project:main Sep 12, 2022
@neutrinoceros neutrinoceros deleted the userdict branch September 12, 2022 10:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Making something better
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants