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

SIM118 Use key in vd instead of key in vd.keys() assumes __iter__ is over keys() #1994

Closed
taldcroft opened this issue Jan 19, 2023 · 3 comments · Fixed by #4966
Closed

SIM118 Use key in vd instead of key in vd.keys() assumes __iter__ is over keys() #1994

taldcroft opened this issue Jan 19, 2023 · 3 comments · Fixed by #4966
Assignees

Comments

@taldcroft
Copy link

Example code:

class ValuesDict:
   """Dict-like container that iterates over the values."""
    def __init__(self, value):
        self.value = value

    def __iter__(self):
        yield from self.values()

    def keys(self):
        return self.value.keys()

    def values(self):
        return self.value.values()


d = {"a": 1, "b": 2, "c": 3}
vd = ValuesDict(d)

for key in vd.keys():
    print(key)

This is the original expected output:

$ python row.py
a
b
c

Applying fixes for SIM118:

$ ruff --select=SIM118 --fix row.py
Found 1 error(s) (1 fixed, 0 remaining).

$ git diff
diff --git a/row.py b/row.py
index 1e7536d..7751a3b 100644
--- a/row.py
+++ b/row.py
@@ -18,5 +18,5 @@ class ValuesDict:
 d = {"a": 1, "b": 2, "c": 3}
 vd = ValuesDict(d)
 
-for key in vd.keys():
+for key in vd:
     print(key)

This changes the code behavior:

$ python row.py                                 
1
2
3
@not-my-profile
Copy link
Contributor

Yes I think we currently have many lints that assume a conventional implementation of some __dunder__ methods. I agree that we should categorize the applicability of such rules, I just opened #1997 for that :)

@charliermarsh
Copy link
Member

Yeah this is probably impossible to avoid completely right now. But we should categorize fixes as described in the issue and consider requiring opt-in for those that could be "dangerous".

@taldcroft
Copy link
Author

Thanks, sounds like a plan. This one certainly caught me by surprise.

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

Successfully merging a pull request may close this issue.

3 participants