Skip to content

Commit 86db3f0

Browse files
committed
Detect and support module aliasing.
In semantic analysis, if we find a simple assignment statement where the rvalue is a module, make the lvalue a direct alias to that same module. Fixes python#1778.
1 parent 39ca936 commit 86db3f0

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

‎mypy/semanal.py‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1515,6 +1515,7 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
15151515
self.process_namedtuple_definition(s)
15161516
self.process_typeddict_definition(s)
15171517
self.process_enum_call(s)
1518+
self.process_module_alias(s)
15181519

15191520
if (len(s.lvalues) == 1 and isinstance(s.lvalues[0], NameExpr) and
15201521
s.lvalues[0].name == '__all__' and s.lvalues[0].kind == GDEF and
@@ -1585,7 +1586,6 @@ def analyze_lvalue(self, lval: Lvalue, nested: bool = False,
15851586
Only if add_global is True, add name to globals table. If nested
15861587
is true, the lvalue is within a tuple or list lvalue expression.
15871588
"""
1588-
15891589
if isinstance(lval, NameExpr):
15901590
# Top-level definitions within some statements (at least while) are
15911591
# not handled in the first pass, so they have to be added now.
@@ -2355,6 +2355,19 @@ def is_classvar(self, typ: Type) -> bool:
23552355
def fail_invalid_classvar(self, context: Context) -> None:
23562356
self.fail('ClassVar can only be used for assignments in class body', context)
23572357

2358+
def process_module_alias(self, s: AssignmentStmt) -> None:
2359+
"""Check if s assigns a module an alias name; if yes, update symbol table."""
2360+
# TODO support more complex forms of module alias (e.g. `x, y = (mod1, mod2)`)
2361+
if (
2362+
len(s.lvalues) != 1
2363+
or not isinstance(s.lvalues[0], NameExpr)
2364+
or not isinstance(s.rvalue, NameExpr)
2365+
):
2366+
return
2367+
rnode = self.lookup(s.rvalue.name, s)
2368+
if rnode and rnode.kind == MODULE_REF:
2369+
self.globals[s.lvalues[0].name] = rnode
2370+
23582371
def process_enum_call(self, s: AssignmentStmt) -> None:
23592372
"""Check if s defines an Enum; if yes, store the definition in symbol table."""
23602373
if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr):

‎test-data/unit/check-modules.test‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1416,3 +1416,13 @@ reveal_type(f()) # E: Revealed type is 'types.ModuleType'
14161416
reveal_type(types) # E: Revealed type is 'types.ModuleType'
14171417

14181418
[builtins fixtures/module.pyi]
1419+
1420+
[case testModuleAlias]
1421+
import m
1422+
m2 = m
1423+
reveal_type(m2.a) # E: Revealed type is 'builtins.str'
1424+
1425+
[file m.py]
1426+
a = 'foo'
1427+
1428+
[builtins fixtures/module.pyi]

0 commit comments

Comments
 (0)