Skip to content

SIM401 triggers on dict like objects that aren't proper dictionaries #15814

Closed
@jogo-openai

Description

@jogo-openai

Description

$ ruff --version
ruff 0.9.3
class Foo:
    def __init__(self):
        self._dict = {}

    def __getitem__(self, key):
        return self._dict[key]

    def __setitem__(self, key, value):
        self._dict[key] = value

    def __iter__(self):
        return self._dict.__iter__()



foo = Foo()
foo['key'] = 'value'


if "key" in foo:
    value = foo["key"]
else:
    value = None

print(value)


# print(foo.get('key', None))
# Triggers `AttributeError: 'Foo' object has no attribute 'get'`

ruff check --fix --unsafe-fixes --diff --select=SIM401 foo.py

--- foo.py
+++ foo.py
@@ -17,10 +17,7 @@
 foo['key'] = 'value'


-if "key" in foo:
-    value = foo["key"]
-else:
-    value = None
+value = foo.get('key', None)

 print(value)


Would fix 1 error.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issueGood for newcomershelp wantedContributions especially welcomeruleImplementing or modifying a lint rule

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions