MartinThoma / flake8-simplify

❄ A flake8 plugin that helps you to simplify code
MIT License
187 stars 19 forks source link

[Adjust Rule] SIM118 - possible issue with objects having a method "keys()" #186

Open GitRon opened 1 year ago

GitRon commented 1 year ago

Example

Imagine this scenario:

class X:
    def keys(self):
        return [1, 2, 3]

x = X()

if 1 in x.keys():
    print('yes')

If I run the linter, I get:

SIM118 Use 1 in x instead of 1 in x.keys()

Which will obviously lead to a crash. I know that I wouldn't name a method keys() but still I think the rule might cause some problems.

We need some check that it's really a dict if we want to auto-remove the keys...

Explanation

We might crash somebodys code when somebody is auto-fixing it (via ruff) or just blindly following the linter.

christianplatta1012 commented 3 months ago

Hi, this actually crashed our code yesterday. Please try to to this only for objects that act like dicts. Maybe something in here can help to identify these structures? https://docs.python.org/3/reference/datamodel.html?emulating-container-types=#emulating-container-types