Skip to content

Commit cd5876c

Browse files
rwbartongvanrossum
authored andcommitted
Allow defining type aliases for Optional[T] (#1653)
This required some follow-on changes that I don't totally understand, but seem like simplifications.
1 parent b242ba9 commit cd5876c

File tree

3 files changed

+14
-4
lines changed

3 files changed

+14
-4
lines changed

mypy/semanal.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1052,14 +1052,15 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
10521052
allow_tuple_literal = isinstance(s.lvalues[-1], (TupleExpr, ListExpr))
10531053
s.type = self.anal_type(s.type, allow_tuple_literal)
10541054
else:
1055-
# For simple assignments, allow binding type aliases.
1055+
# For simple assignments at top level, allow binding type aliases.
10561056
if (s.type is None and len(s.lvalues) == 1 and
1057-
isinstance(s.lvalues[0], NameExpr)):
1057+
isinstance(s.lvalues[0], NameExpr) and
1058+
not self.is_func_scope() and not self.type):
10581059
res = analyze_type_alias(s.rvalue,
10591060
self.lookup_qualified,
10601061
self.lookup_fully_qualified,
10611062
self.fail)
1062-
if res and (not isinstance(res, Instance) or cast(Instance, res).args):
1063+
if res:
10631064
# TODO: What if this gets reassigned?
10641065
name = cast(NameExpr, s.lvalues[0])
10651066
node = self.lookup(name.name, name)

mypy/test/data/check-type-aliases.test

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,14 @@ f(1)
1313
f('')
1414
f(()) # E: Argument 1 to "f" has incompatible type "Tuple[]"; expected "Union[int, str]"
1515

16+
[case testOptionalTypeAlias]
17+
from typing import Optional
18+
O = Optional[int]
19+
def f(x: O) -> None: pass
20+
f(1)
21+
f(None)
22+
f(()) # E: Argument 1 to "f" has incompatible type "Tuple[]"; expected "int"
23+
1624
[case testTupleTypeAlias]
1725
from typing import Tuple
1826
T = Tuple[int, str]

mypy/typeanal.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
from mypy import nodes
1919

2020

21-
type_constructors = ['typing.Tuple', 'typing.Union', 'typing.Callable']
21+
type_constructors = ['typing.Tuple', 'typing.Union', 'typing.Optional',
22+
'typing.Callable']
2223

2324

2425
def analyze_type_alias(node: Node,

0 commit comments

Comments
 (0)