Skip to content

Commit

Permalink
stubgen: Allow aliases below the top level (#14388)
Browse files Browse the repository at this point in the history
  • Loading branch information
chadrik authored Jan 30, 2023
1 parent 1d247ea commit 7c14eba
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 13 deletions.
5 changes: 2 additions & 3 deletions mypy/stubgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -999,8 +999,7 @@ def visit_assignment_stmt(self, o: AssignmentStmt) -> None:
self.process_namedtuple(lvalue, o.rvalue)
continue
if (
self.is_top_level()
and isinstance(lvalue, NameExpr)
isinstance(lvalue, NameExpr)
and not self.is_private_name(lvalue.name)
and
# it is never an alias with explicit annotation
Expand Down Expand Up @@ -1118,7 +1117,7 @@ def is_alias_expression(self, expr: Expression, top_level: bool = True) -> bool:

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

Expand Down
60 changes: 50 additions & 10 deletions test-data/unit/stubgen.test
Original file line number Diff line number Diff line change
Expand Up @@ -947,16 +947,6 @@ from typing import Any

alias = Container[Any]

[case testAliasOnlyToplevel]
class Foo:
alias = str

[out]
from _typeshed import Incomplete

class Foo:
alias: Incomplete

[case testAliasExceptions]
noalias1 = None
noalias2 = ...
Expand All @@ -969,6 +959,56 @@ noalias1: Incomplete
noalias2: Incomplete
noalias3: bool

[case testComplexAlias]
# modules: main a

from a import valid

def func() -> int:
return 2

aliased_func = func
int_value = 1

class A:
cls_var = valid

def __init__(self, arg: str) -> None:
self.self_var = arg

def meth(self) -> None:
func_value = int_value

alias_meth = meth
alias_func = func
alias_alias_func = aliased_func
int_value = int_value

[file a.py]
valid : list[int] = [1, 2, 3]


[out]
# main.pyi
from _typeshed import Incomplete
from a import valid

def func() -> int: ...
aliased_func = func
int_value: int

class A:
cls_var = valid
self_var: Incomplete
def __init__(self, arg: str) -> None: ...
def meth(self) -> None: ...
alias_meth = meth
alias_func = func
alias_alias_func = aliased_func
int_value = int_value
# a.pyi
valid: list[int]

-- More features/fixes:
-- do not export deleted names

Expand Down

0 comments on commit 7c14eba

Please sign in to comment.