Skip to content

Don't narrow Type[X] with a metaclass #10424

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

Merged
merged 1 commit into from
May 5, 2021
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
5 changes: 5 additions & 0 deletions mypy/meet.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ def narrow_declared_type(declared: Type, narrowed: Type) -> Type:
return narrowed
elif isinstance(declared, TypeType) and isinstance(narrowed, TypeType):
return TypeType.make_normalized(narrow_declared_type(declared.item, narrowed.item))
elif (isinstance(declared, TypeType)
and isinstance(narrowed, Instance)
and narrowed.type.is_metaclass()):
# We'd need intersection types, so give up.
return declared
elif isinstance(declared, (Instance, TupleType, TypeType, LiteralType)):
return meet_types(declared, narrowed)
elif isinstance(declared, TypedDictType) and isinstance(narrowed, Instance):
Expand Down
20 changes: 20 additions & 0 deletions test-data/unit/check-narrowing.test
Original file line number Diff line number Diff line change
Expand Up @@ -1053,3 +1053,23 @@ def f(d: Union[Foo, Bar]) -> None:
d['x']
reveal_type(d) # N: Revealed type is "TypedDict('__main__.Foo', {'tag': Literal[__main__.E.FOO], 'x': builtins.int})"
[builtins fixtures/dict.pyi]

[case testNarrowingUsingMetaclass]
# flags: --strict-optional
from typing import Type

class M(type):
pass

class C: pass

def f(t: Type[C]) -> None:
if type(t) is M:
reveal_type(t) # N: Revealed type is "Type[__main__.C]"
else:
reveal_type(t) # N: Revealed type is "Type[__main__.C]"
if type(t) is not M:
reveal_type(t) # N: Revealed type is "Type[__main__.C]"
else:
reveal_type(t) # N: Revealed type is "Type[__main__.C]"
reveal_type(t) # N: Revealed type is "Type[__main__.C]"