dosisod / refurb

A tool for refurbishing and modernizing Python codebases
GNU General Public License v3.0
2.48k stars 54 forks source link

[Enhancement]: subclassing `collections.UserDict` over `dict` #323

Closed jamesbraza closed 9 months ago

jamesbraza commented 9 months ago

Overview

There is a built-in data structure collections.UserDict that is designed for subclasses of dict.

However, I don't think many people are aware of collections.UserDict, instead I see lots of dict subclasses. I propose a rule to suggest this change.

This request was made as of refurb version 1.28.0.

Proposal

Here is basically what the rule would do:

+++ from collections import UserDict

--- class MyDict(dict):
+++ class MyUserDict(UserDict):
    pass
dosisod commented 9 months ago

Thank you @jamesbraza for opening this! I agree, this would be a great check to add.

There might be some sneaky reason why some people extend from dict instead of UserDict, but like you said, I assume most people don't know about UserDict.

dosisod commented 9 months ago

I would also extend this to include UserList and UserString, since it seems people also like to extend from list and str.

jamesbraza commented 9 months ago

Oh wow that was quick turnaround, and thank you @dosisod! I guess the isinstance(some_user_dict, dict) is a decent gotcha, so you made the right call having it be opt-in. Thank you!