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

Skip to content

Commit 8bad612

Browse files
committed
Disallow "import mod.submod as m", because the result is ambiguous. Does it
load mod.submod as m, or mod as m ? Both can be achieved differently, and unambiguously. Also attempt to document this restriction (editor appreciated!) Note that this is an artificial check during compile, because incorporating this in the grammar is hard, and then adjusting the compiler to do the right thing with the right nodes is harder.
1 parent 15446d3 commit 8bad612

2 files changed

Lines changed: 8 additions & 2 deletions

File tree

Doc/ref/ref6.tex

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -498,7 +498,12 @@ \section{The \keyword{import} statement \label{import}}
498498
The first form of \keyword{import} statement binds the module name in the
499499
local namespace to the module object, and then goes on to import the
500500
next identifier, if any. If the module name is followed by \keyword{as},
501-
the name following \keyword{as} is used as the local name for the module.
501+
the name following \keyword{as} is used as the local name for the module. To
502+
avoid confusion, you cannot import sub-modules 'as' a different
503+
local name. So 'import module as m' is legal, but 'import module.submod as
504+
s' is not. The latter should be written as 'from module import submod as s',
505+
see below.
506+
502507
The \keyword{from} form does not bind the module name: it goes through the
503508
list of identifiers, looks each one of them up in the module found in step
504509
(1), and binds the name in the local namespace to the object thus found.

Python/compile.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2139,7 +2139,8 @@ com_import_stmt(struct compiling *c, node *n)
21392139
com_addopname(c, IMPORT_NAME, CHILD(subn, 0));
21402140
com_push(c, 1);
21412141
if (NCH(subn) > 1) {
2142-
if (strcmp(STR(CHILD(subn, 1)), "as") != 0) {
2142+
if (strcmp(STR(CHILD(subn, 1)), "as") != 0 ||
2143+
NCH(CHILD(subn, 0)) > 1) {
21432144
com_error(c, PyExc_SyntaxError,
21442145
"invalid syntax");
21452146
return;

0 commit comments

Comments
 (0)