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

Detect incorrect key types passed to dict.__getitem__ #468

Merged
merged 2 commits into from
Feb 6, 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

- Detect incorrect key types passed to `dict.__getitem__` (#468)
- Pick up the signature of `open()` from typeshed correctly (#463)
- Do not strip away generic parameters explicitly set to
`Any` (#467)
Expand Down
9 changes: 9 additions & 0 deletions pyanalyze/implementation.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,15 @@ def inner(key: Value) -> Value:
return AnyValue(AnySource.error)
return val
elif isinstance(self_value, TypedValue):
key_type = self_value.get_generic_arg_for_type(dict, ctx.visitor, 0)
can_assign = key_type.can_assign(key, ctx.visitor)
if isinstance(can_assign, CanAssignError):
ctx.show_error(
f"Dictionary does not accept keys of type {key}",
error_code=ErrorCode.incompatible_argument,
detail=str(can_assign),
arg="key",
)
return self_value.get_generic_arg_for_type(dict, ctx.visitor, 1)
else:
return AnyValue(AnySource.inference)
Expand Down
4 changes: 2 additions & 2 deletions pyanalyze/stacked_scopes.py
Original file line number Diff line number Diff line change
Expand Up @@ -947,8 +947,8 @@ class FunctionScope(Scope):
name_to_current_definition_nodes: SubScope
usage_to_definition_nodes: Dict[Tuple[Node, Varname], List[Node]]
definition_node_to_value: Dict[Node, Value]
name_to_all_definition_nodes: Dict[str, Set[Node]]
name_to_composites: Dict[str, Set[CompositeVariable]]
name_to_all_definition_nodes: Dict[Varname, Set[Node]]
name_to_composites: Dict[Varname, Set[CompositeVariable]]
referencing_value_vars: Dict[Varname, Value]
accessed_from_special_nodes: Set[Varname]
current_loop_scopes: List[SubScope]
Expand Down
2 changes: 2 additions & 0 deletions pyanalyze/test_implementation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1078,6 +1078,8 @@ def capybara(
assert_is_value(nd[1], TypedValue(str))
assert_is_value(rev[1], TypedValue(str))

dct[1] # E: incompatible_argument


class TestDictSetItem(TestNameCheckVisitorBase):
@assert_passes()
Expand Down