Skip to content

Commit

Permalink
Detect incorrect key types passed to dict.__getitem__ (#468)
Browse files Browse the repository at this point in the history
  • Loading branch information
JelleZijlstra authored Feb 6, 2022
1 parent ffe603d commit 0bf4700
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 2 deletions.
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

0 comments on commit 0bf4700

Please sign in to comment.