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

Fix type inference for Mapping #623

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 4 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- Fix type inference for subscriptingon `Mapping`
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved

## Version 0.10.0 (May 10, 2023)

- Infer the signature for built-in static methods, such as `dict.fromkeys` (#619)
Expand Down
60 changes: 47 additions & 13 deletions pyanalyze/implementation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from .signature import (
ANY_SIGNATURE,
CallContext,
Impl,
ImplReturn,
ParameterKind,
Signature,
Expand Down Expand Up @@ -530,6 +531,34 @@ def _dict_setitem_impl(ctx: CallContext) -> ImplReturn:
return _add_pairs_to_dict(ctx.vars["self"], [pair], ctx, varname)


def _mapping_getitem_impl(ctx: CallContext) -> ImplReturn:
def inner(key: Value) -> Value:
self_value = ctx.vars["self"]
if isinstance(self_value, AnnotatedValue):
self_value = self_value.value
if not _check_dict_key_hashability(key, ctx, "k"):
return AnyValue(AnySource.error)
if isinstance(self_value, TypedValue):
key_type = self_value.get_generic_arg_for_type(
collections.abc.Mapping, ctx.visitor, 0
)
can_assign = key_type.can_assign(key, ctx.visitor)
if isinstance(can_assign, CanAssignError):
ctx.show_error(
f"Mapping 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(
collections.abc.Mapping, ctx.visitor, 1
)
else:
return AnyValue(AnySource.inference)

return flatten_unions(inner, ctx.vars["k"])


def _dict_getitem_impl(ctx: CallContext) -> ImplReturn:
def inner(key: Value) -> Value:
self_value = ctx.vars["self"]
Expand Down Expand Up @@ -602,6 +631,22 @@ def inner(key: Value) -> Value:
return flatten_unions(inner, ctx.vars["k"])


def _make_mapping_getitem_sig(typ: type, impl: Impl) -> Signature:
return Signature.make(
[
SigParameter(
"self",
_POS_ONLY,
annotation=GenericValue(typ, [TypeVarValue(K), TypeVarValue(V)]),
),
SigParameter("k", _POS_ONLY),
],
callable=typ.__getitem__,
impl=impl,
return_annotation=TypeVarValue(V),
)


def _dict_get_impl(ctx: CallContext) -> ImplReturn:
default = ctx.vars["default"]

Expand Down Expand Up @@ -1605,19 +1650,8 @@ def get_default_argspecs() -> Dict[object, Signature]:
impl=_dict_setitem_impl,
return_annotation=KnownValue(None),
),
Signature.make(
[
SigParameter(
"self",
_POS_ONLY,
annotation=GenericValue(dict, [TypeVarValue(K), TypeVarValue(V)]),
),
SigParameter("k", _POS_ONLY),
],
callable=dict.__getitem__,
impl=_dict_getitem_impl,
return_annotation=TypeVarValue(V),
),
_make_mapping_getitem_sig(dict, _dict_getitem_impl),
_make_mapping_getitem_sig(collections.abc.Mapping, _mapping_getitem_impl),
Signature.make(
[
SigParameter("self", _POS_ONLY, annotation=TypedValue(dict)),
Expand Down
24 changes: 24 additions & 0 deletions pyanalyze/test_implementation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1169,6 +1169,30 @@ def capybara(d: dict, t: Type[int]):
d[int]
d[t]

@assert_passes()
def test_mapping(self):
from typing import Mapping
from typing_extensions import assert_type

def capybara(m: Mapping[str, int], unannotated):
assert_type(m["x"], int)
assert_type(m[unannotated], int)
m[1] # E: incompatible_argument
m[{}] # E: unhashable_key
m["x"] = 3 # E: unsupported_operation

@assert_passes()
def test_mutable_mapping(self):
from typing import MutableMapping
from typing_extensions import assert_type

def capybara(m: MutableMapping[str, int], unannotated):
assert_type(m["x"], int)
assert_type(m[unannotated], int)
m[1] # E: incompatible_argument
m[{}] # E: unhashable_key
m["x"] = 3


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