Skip to content

Always flatten unions on creation #3298

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 3 commits into from
May 2, 2017
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
13 changes: 12 additions & 1 deletion mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -987,7 +987,7 @@ class UnionType(Type):
items = None # type: List[Type]

def __init__(self, items: List[Type], line: int = -1, column: int = -1) -> None:
self.items = items
self.items = flatten_nested_unions(items)
self.can_be_true = any(item.can_be_true for item in items)
self.can_be_false = any(item.can_be_false for item in items)
super().__init__(line, column)
Expand Down Expand Up @@ -1732,6 +1732,17 @@ def get_type_vars(typ: Type) -> List[TypeVarType]:
return tvars


def flatten_nested_unions(types: Iterable[Type]) -> List[Type]:
"""Flatten nested unions in a type list."""
flat_items = [] # type: List[Type]
for tp in types:
if isinstance(tp, UnionType):
flat_items.extend(flatten_nested_unions(tp.items))
else:
flat_items.append(tp)
return flat_items


def union_items(typ: Type) -> List[Type]:
"""Return the flattened items of a union type.

Expand Down
15 changes: 15 additions & 0 deletions test-data/unit/check-unions.test
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,21 @@ reveal_type(l) \
# E: Revealed type is 'builtins.list[Union[builtins.bool, builtins.int, builtins.float, builtins.str]]'
[builtins fixtures/list.pyi]

[case testNestedUnionsProcessedCorrectly]
from typing import Union

class A: pass
class B: pass
class C: pass

def foo(bar: Union[Union[A, B], C]) -> None:
if isinstance(bar, A):
reveal_type(bar) # E: Revealed type is '__main__.A'
else:
reveal_type(bar) # E: Revealed type is 'Union[__main__.B, __main__.C]'
[builtins fixtures/isinstance.pyi]
[out]

[case testAssignAnyToUnion]
from typing import Union, Any
x: Union[int, str]
Expand Down