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

Support "in" on objects with __getitem__ #564

Merged
merged 1 commit into from
Nov 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

- Support `in` on objects with only `__getitem__` (#564)
- Add support for `except*` (PEP 654) (#562)
- Add type inference support for more constructs in `except` and `except*` (#562)

Expand Down
26 changes: 26 additions & 0 deletions pyanalyze/name_check_visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3175,6 +3175,32 @@ def _visit_binop_no_mvv(
type(op)
]
if rmethod is None:
# "in" falls back to __getitem__ if __contains__ is not defined
if method == "__contains__":
with self.catch_errors() as contains_errors:
contains_result = self._check_dunder_call(
source_node,
left_composite,
method,
[right_composite],
allow_call=allow_call,
)
if not contains_errors:
return contains_result

with self.catch_errors() as getitem_errors:
self._check_dunder_call(
source_node,
left_composite,
"__getitem__",
[right_composite],
allow_call=allow_call,
)
if not getitem_errors:
return TypedValue(bool) # Always returns a bool
self.show_caught_errors(contains_errors)
return TypedValue(bool)

return self._check_dunder_call(
source_node,
left_composite,
Expand Down
11 changes: 11 additions & 0 deletions pyanalyze/test_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,17 @@ def comparison(i: int, f: float, s: str, os: Optional[str]):
s > None
s > os

@assert_passes()
def test_contains(self):
class OnlyGetitem:
def __getitem__(self, x: int) -> int:
return x

def capybara(x: int, ogi: OnlyGetitem):
1 in x # E: unsupported_operation
1 in ogi
"x" in ogi # E: unsupported_operation

@assert_passes()
def test_failing_eq(self):
class FlakyCapybara:
Expand Down