Skip to content

Commit 21ff1a8

Browse files
committed
Make Union[str, None] equivalent to str
Closes #572.
1 parent 4c7edba commit 21ff1a8

File tree

3 files changed

+51
-1
lines changed

3 files changed

+51
-1
lines changed

mypy/test/data/check-unions.test

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,3 +97,9 @@ s = ''
9797
s = f(int)
9898
s = f(1) # E: Incompatible types in assignment (expression has type "int", variable has type "str")
9999
x = f(int) # E: Incompatible types in assignment (expression has type "str", variable has type "int")
100+
101+
[case testUnionWithNoneItem]
102+
from typing import Union
103+
def f() -> Union[int, None]: pass
104+
x = 1
105+
x = f()

mypy/test/data/semanal-types.test

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1466,3 +1466,45 @@ MypyFile:1(
14661466
BaseType(
14671467
__main__.B)
14681468
PassStmt:7()))
1469+
1470+
[case testUnionType]
1471+
from typing import Union
1472+
def f(x: Union[int, str]) -> None: pass
1473+
[out]
1474+
MypyFile:1(
1475+
ImportFrom:1(typing, [Union : Union])
1476+
FuncDef:2(
1477+
f
1478+
Args(
1479+
Var(x))
1480+
def (x: Union[builtins.int, builtins.str])
1481+
Block:2(
1482+
PassStmt:2())))
1483+
1484+
[case testUnionTypeWithNoneItem]
1485+
from typing import Union
1486+
def f(x: Union[int, None]) -> None: pass
1487+
[out]
1488+
MypyFile:1(
1489+
ImportFrom:1(typing, [Union : Union])
1490+
FuncDef:2(
1491+
f
1492+
Args(
1493+
Var(x))
1494+
def (x: builtins.int)
1495+
Block:2(
1496+
PassStmt:2())))
1497+
1498+
[case testUnionTypeWithNoneItemAndTwoItems]
1499+
from typing import Union
1500+
def f(x: Union[int, None, str]) -> None: pass
1501+
[out]
1502+
MypyFile:1(
1503+
ImportFrom:1(typing, [Union : Union])
1504+
FuncDef:2(
1505+
f
1506+
Args(
1507+
Var(x))
1508+
def (x: Union[builtins.int, builtins.str])
1509+
Block:2(
1510+
PassStmt:2())))

mypy/typeanal.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,9 @@ def visit_unbound_type(self, t: UnboundType) -> Type:
8989
return TupleType(self.anal_array(t.args),
9090
self.builtin_type('builtins.tuple'))
9191
elif sym.node.fullname() == 'typing.Union':
92-
return UnionType(self.anal_array(t.args))
92+
items = self.anal_array(t.args)
93+
items = [item for item in items if not isinstance(item, Void)]
94+
return UnionType.make_union(items)
9395
elif sym.node.fullname() == 'typing.Callable':
9496
return self.analyze_function_type(t)
9597
elif sym.kind == TYPE_ALIAS:

0 commit comments

Comments
 (0)