Skip to content

Type alias stubgen fix #18960

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 10 commits into from
May 1, 2025
27 changes: 20 additions & 7 deletions mypy/stubgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -920,13 +920,20 @@ def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
continue
if (
isinstance(lvalue, NameExpr)
and not self.is_private_name(lvalue.name)
# it is never an alias with explicit annotation
and not o.unanalyzed_type
and self.is_alias_expression(o.rvalue)
and not self.is_private_name(lvalue.name)
):
self.process_typealias(lvalue, o.rvalue)
continue
is_explicit_type_alias = (
o.unanalyzed_type and getattr(o.type, "name", None) == "TypeAlias"
)
if is_explicit_type_alias:
self.process_typealias(lvalue, o.rvalue, is_explicit_type_alias=True)
continue

if not o.unanalyzed_type:
self.process_typealias(lvalue, o.rvalue)
continue

if isinstance(lvalue, (TupleExpr, ListExpr)):
items = lvalue.items
if isinstance(o.unanalyzed_type, TupleType): # type: ignore[misc]
Expand Down Expand Up @@ -1139,9 +1146,15 @@ def is_alias_expression(self, expr: Expression, top_level: bool = True) -> bool:
else:
return False

def process_typealias(self, lvalue: NameExpr, rvalue: Expression) -> None:
def process_typealias(
self, lvalue: NameExpr, rvalue: Expression, is_explicit_type_alias: bool = False
) -> None:
p = AliasPrinter(self)
self.add(f"{self._indent}{lvalue.name} = {rvalue.accept(p)}\n")
if is_explicit_type_alias:
self.import_tracker.require_name("TypeAlias")
self.add(f"{self._indent}{lvalue.name}: TypeAlias = {rvalue.accept(p)}\n")
else:
self.add(f"{self._indent}{lvalue.name} = {rvalue.accept(p)}\n")
self.record_name(lvalue.name)
self._vars[-1].append(lvalue.name)

Expand Down
13 changes: 13 additions & 0 deletions test-data/unit/stubgen.test
Original file line number Diff line number Diff line change
Expand Up @@ -1544,6 +1544,19 @@ from typing import TypeVar
T = TypeVar('T')
alias = Union[T, List[T]]

[case testExplicitTypeAlias]
from typing import TypeAlias

explicit_alias: TypeAlias = tuple[int, str]
implicit_alias = list[int]

[out]
from typing import TypeAlias

explicit_alias: TypeAlias = tuple[int, str]
implicit_alias = list[int]


[case testEllipsisAliasPreserved]

alias = Tuple[int, ...]
Expand Down