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

Get empty dict issue #18273

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
24 changes: 24 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,30 @@ def module_type(self, node: MypyFile) -> Instance:

def visit_call_expr(self, e: CallExpr, allow_none_return: bool = False) -> Type:
"""Type check a call expression."""
if (
self.refers_to_typeddict(e.callee)
or isinstance(e.callee, IndexExpr)
and self.refers_to_typeddict(e.callee.base)
):
typeddict_callable = get_proper_type(self.accept(e.callee, is_callee=True))
if isinstance(typeddict_callable, CallableType):
typeddict_type = get_proper_type(typeddict_callable.ret_type)
assert isinstance(typeddict_type, TypedDictType)
return self.check_typeddict_call(e, typeddict_type, typeddict_callable)

# Add logic to handle the `get` method
if isinstance(e.callee, MemberExpr) and e.callee.name == "get":
dict_type = self.accept(e.callee.expr)
if isinstance(dict_type, Instance) and dict_type.type.fullname == "builtins.dict":
key_type = self.accept(e.args[0])
if len(e.args) == 2:
default_type = self.accept(e.args[1])
return UnionType.make_union([dict_type.args[1], default_type])
return UnionType.make_union([dict_type.args[1], NoneType()])
elif isinstance(dict_type, Instance) and dict_type.type.fullname == "builtins.dict":
# Handle empty dictionary case
return AnyType(TypeOfAny.special_form)

if e.analyzed:
if isinstance(e.analyzed, NamedTupleExpr) and not e.analyzed.is_typed:
# Type check the arguments, but ignore the results. This relies
Expand Down
18 changes: 18 additions & 0 deletions mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from mypy.maptype import map_instance_to_supertype
from mypy.messages import MessageBuilder
from mypy.nodes import (
ARG_OPT,
ARG_POS,
ARG_STAR,
ARG_STAR2,
Expand Down Expand Up @@ -203,6 +204,11 @@ def analyze_member_access(
no_deferral=no_deferral,
is_self=is_self,
)

if name == "get" and isinstance(typ, Instance) and typ.type.fullname == "builtins.dict":
# Handle overload resolution for dict.get
return analyze_dict_get(typ, context)

result = _analyze_member_access(name, typ, mx, override_info)
possible_literal = get_proper_type(result)
if (
Expand All @@ -215,6 +221,18 @@ def analyze_member_access(
return result


def analyze_dict_get(self, typ: Instance, context: Context) -> Type:
key_type = typ.args[0]
value_type = typ.args[1]
return CallableType(
[key_type, value_type],
[ARG_POS, ARG_OPT],
[None, None],
UnionType.make_union([value_type, NoneType()]),
self.named_type("builtins.function"),
)


def _analyze_member_access(
name: str, typ: Type, mx: MemberContext, override_info: TypeInfo | None = None
) -> Type:
Expand Down
19 changes: 19 additions & 0 deletions test-data/unit/check-dict-get.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[case testDictGetEmpty]
def testDictGetEmpty() -> None:
x = {}.get("x")
reveal_type(x) # N: Revealed type is "None"

[case testDictGetWithDefault]
def testDictGetWithDefault() -> None:
x = {}.get("x", 42)
reveal_type(x) # N: Revealed type is "int"

[case testDictGetExistingKey]
def testDictGetExistingKey() -> None:
x = {"a": 1}.get("a")
reveal_type(x) # N: Revealed type is "int"

[case testDictGetMissingKey]
def testDictGetMissingKey() -> None:
x = {"a": 1}.get("b")
reveal_type(x) # N: Revealed type is "None"
Loading