Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9b8a92e

Browse files
committed
Don't export imported modules in stubs unless using 'as'
To import module m in a stub, you must now use something like 'import m as m'. This behavior conforms to PEP 484.
1 parent 73300e4 commit 9b8a92e

2 files changed

Lines changed: 41 additions & 8 deletions

File tree

mypy/semanal.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -737,16 +737,22 @@ def bind_class_type_variables_in_symbol_table(
737737

738738
def visit_import(self, i: Import) -> None:
739739
for id, as_id in i.ids:
740-
if as_id is not None and as_id != id:
741-
self.add_module_symbol(id, as_id, i)
740+
if as_id is not None:
741+
self.add_module_symbol(id, as_id, module_public=True, context=i)
742742
else:
743+
# Modules imported in a stub file without using 'as x' won't get exported when
744+
# doing 'from m import *'.
745+
module_public = not self.is_stub_file
743746
base = id.split('.')[0]
744-
self.add_module_symbol(base, base, i)
747+
self.add_module_symbol(base, base, module_public=module_public,
748+
context=i)
745749

746-
def add_module_symbol(self, id: str, as_id: str, context: Context) -> None:
750+
def add_module_symbol(self, id: str, as_id: str, module_public: bool,
751+
context: Context) -> None:
747752
if id in self.modules:
748753
m = self.modules[id]
749-
self.add_symbol(as_id, SymbolTableNode(MODULE_REF, m, self.cur_mod_id), context)
754+
self.add_symbol(as_id, SymbolTableNode(MODULE_REF, m, self.cur_mod_id,
755+
module_public=module_public), context)
750756
else:
751757
self.add_unknown_symbol(as_id, context)
752758

mypy/test/data/semanal-modules.test

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -783,8 +783,7 @@ from m.x import nonexistent
783783
main:1: note: In module imported here:
784784
tmp/m/x.py:1: error: Module has no attribute 'nonexistent'
785785

786-
787-
[case testImportAsInStubs]
786+
[case testFromImportAsInStub]
788787
from m import *
789788
x
790789
y # E: Name 'y' is not defined
@@ -796,7 +795,7 @@ x = 1
796795
y = 2
797796
[out]
798797

799-
[case testImportAsInNonStub]
798+
[case testFromImportAsInNonStub]
800799
from m_ import *
801800
x
802801
y
@@ -813,3 +812,31 @@ MypyFile:1(
813812
NameExpr(x [m2_.x]))
814813
ExpressionStmt:3(
815814
NameExpr(y [m2_.y])))
815+
816+
[case testImportAsInStub]
817+
from m import *
818+
m2
819+
m3 # E: Name 'm3' is not defined
820+
[file m.pyi]
821+
import m2 as m2
822+
import m3
823+
[file m2.py]
824+
[file m3.py]
825+
[out]
826+
827+
[case testImportAsInNonStub]
828+
from m_ import *
829+
m2_
830+
m3_
831+
[file m_.py]
832+
import m2_ as m2_
833+
import m3_
834+
[file m2_.py]
835+
[file m3_.py]
836+
[out]
837+
MypyFile:1(
838+
ImportAll:1(m_)
839+
ExpressionStmt:2(
840+
NameExpr(m2_))
841+
ExpressionStmt:3(
842+
NameExpr(m3_)))

0 commit comments

Comments
 (0)