FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Fix TypeIs narrowing to NewType by nightcityblade · Pull Request #22179 · python/mypy · GitHub

Repository navigation

Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (1) .test  (1) All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
14 changes: 7 additions & 7 deletions mypy/checker.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -8859,13 +8859,13 @@ def conditional_types(

proposed_type = make_simplified_union([type_range.item for type_range in proposed_type_ranges])
items = proposed_type.items if isinstance(proposed_type, UnionType) else [proposed_type]
for i in range(len(items)):
item = get_proper_type(items[i])
# Avoid ever narrowing to a NewType. The principle is values of NewType should only be
# produce by explicit wrapping
while isinstance(item, Instance) and item.type.is_newtype:
item = item.type.bases[0]
items[i] = item
if consider_runtime_isinstance:
for i in range(len(items)):
item = get_proper_type(items[i])
# Runtime checks can't distinguish a NewType from its base type.
while isinstance(item, Instance) and item.type.is_newtype:
item = item.type.bases[0]
items[i] = item
proposed_type = get_proper_type(UnionType.make_union(items))

if isinstance(p_current_type, AnyType):
Expand Down
14 changes: 14 additions & 0 deletions test-data/unit/check-typeis.test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,20 @@ def main(a: object) -> None:
reveal_type(a) # N: Revealed type is "builtins.object"
[builtins fixtures/tuple.pyi]

[case testTypeIsNewType]
from typing import NewType
from typing_extensions import TypeIs

Admin = NewType("Admin", str)
def is_admin(value: str) -> TypeIs[Admin]: ...

def f(value: str) -> None:
if is_admin(value):
reveal_type(value) # N: Revealed type is "__main__.Admin"
else:
reveal_type(value) # N: Revealed type is "builtins.str"
[builtins fixtures/tuple.pyi]

[case testTypeIsElif]
from typing_extensions import TypeIs
from typing import Union
Expand Down
Loading

Back | FazBrowse Home | New Git URL