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

Make None promotable to object, not a subclass, when resolving overloads #3763

Closed
wants to merge 4 commits into from
Closed
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
10 changes: 8 additions & 2 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -2784,6 +2784,9 @@ def overload_arg_similarity(actual: Type, formal: Type) -> int:

The distinction is important in cases where multiple overload items match. We want
give priority to higher similarity matches.

If strict-optional is enabled, we count (None -> object) as a promotion, even though it's
treated as a subtype elsewhere, to enable overloads between None and object.
"""
# Replace type variables with their upper bounds. Overloading
# resolution is based on runtime behavior which erases type
Expand All @@ -2809,9 +2812,12 @@ def overload_arg_similarity(actual: Type, formal: Type) -> int:
# NoneTyp matches anything if we're not doing strict Optional checking
return 2
else:
# NoneType is a subtype of object
# HACK: As a special case, we don't consider NoneType as a subtype of object here, as
# otherwise you wouldn't be able to define overloads between object and None. This is
# important e.g. for typing descriptors, which get an object when acting as an instance
# property and None when acting as a class property.
if isinstance(formal, Instance) and formal.type.fullname() == "builtins.object":
return 2
return 1
if isinstance(actual, UnionType):
return max(overload_arg_similarity(item, formal)
for item in actual.relevant_items())
Expand Down
11 changes: 11 additions & 0 deletions test-data/unit/check-optional.test
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,17 @@ def f(x: int) -> int: pass
reveal_type(f(None)) # E: Revealed type is 'builtins.str'
reveal_type(f(0)) # E: Revealed type is 'builtins.int'

[case testOverloadWithObject]
from foo import *
[file foo.pyi]
from typing import overload
@overload
def f(x: None) -> str: pass
@overload
def f(x: object) -> int: pass
reveal_type(f(None)) # E: Revealed type is 'builtins.str'
reveal_type(f(0)) # E: Revealed type is 'builtins.int'

[case testOptionalTypeOrTypePlain]
from typing import Optional
def f(a: Optional[int]) -> int:
Expand Down