Skip to content

Commit d24a9af

Browse files
committed
Don't reexport star-imported symbols when implicit reexports are disabled
Currently, in regular files, symbols imported into module A with `from B import *` are considered explicitly exported from module B as well, i.e. they are considered part of module's B public API. This behavior makes sense in stub files as a shorthand (and is specified in PEP 484), but for regular files I think it is better to be explicit: add the symbols to `__all__`. Further discussion: python#7042 (comment)
1 parent 133ba62 commit d24a9af

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

mypy/semanal.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1869,7 +1869,15 @@ def visit_import_all(self, i: ImportAll) -> None:
18691869
if self.process_import_over_existing_name(
18701870
name, existing_symbol, node, i):
18711871
continue
1872-
self.add_imported_symbol(name, node, i)
1872+
# In stub files, `from x import *` always reexports the symbols.
1873+
# In regular files, only if implicit reexports are enabled.
1874+
module_public = (
1875+
self.is_stub_file
1876+
or self.options.implicit_reexport
1877+
)
1878+
self.add_imported_symbol(name, node, i,
1879+
module_public=module_public,
1880+
module_hidden=not module_public)
18731881
else:
18741882
# Don't add any dummy symbols for 'from x import *' if 'x' is unknown.
18751883
pass

test-data/unit/check-flags.test

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1158,6 +1158,29 @@ __all__ = ('b',)
11581158
[out]
11591159
main:2: error: Module 'other_module_2' has no attribute 'a'
11601160

1161+
[case testNoImplicitReexportStarConsideredImplicit]
1162+
# flags: --no-implicit-reexport
1163+
from other_module_2 import a
1164+
[file other_module_1.py]
1165+
a = 5
1166+
[file other_module_2.py]
1167+
from other_module_1 import *
1168+
[out]
1169+
main:2: error: Module 'other_module_2' has no attribute 'a'
1170+
1171+
[case testNoImplicitReexportStarCanBeReexportedWithAll]
1172+
# flags: --no-implicit-reexport
1173+
from other_module_2 import a
1174+
from other_module_2 import b
1175+
[file other_module_1.py]
1176+
a = 5
1177+
b = 6
1178+
[file other_module_2.py]
1179+
from other_module_1 import *
1180+
__all__ = ('b',)
1181+
[out]
1182+
main:2: error: Module 'other_module_2' has no attribute 'a'
1183+
11611184
[case testNoImplicitReexportMypyIni]
11621185
# flags: --config-file tmp/mypy.ini
11631186
from other_module_2 import a

0 commit comments

Comments
 (0)