Skip to content

Brute-Forceing keys in __getitem__ #137473

@LukeGrainwalker

Description

@LukeGrainwalker

Bug report

Bug description:

I have encountered a problem when using the __getitem__ method in cpython 3.10.12 and 3.15.0a0:
When a class has a __getitem__ but not a __contains__ method python seems to brute force the key when using the keyword in. I know this must be intentional (brute forcing does not happen by accident). But in the code, i encountered this in, i was using strings as keys, which python will never brute force. In this case it will never return. From a users perspective it would be more helpful to have a clear error message instead.

class test:
    def __init__(self):
        pass
    def __getitem__(self, key):
        print(key)

if "this is a test" in test():
    print("it is in it?")

this will count up to infinity!

I hope this will not drown among the 7000 Issues.
Thanks for reviewing this and God Bless you!

CPython versions tested on:

3.15, CPython main branch, 3.10

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions