'Why is import * not valid syntax in Python 3?

I recently tried this code, just to satisfy a curiosity.

from * import * as *

if __name__ == '__main__':
    z = *.zeros((3,3))
    print(z)

Can somebody tell me why import * is not considered a valid option? I really would like an option to just import every library installed/recognized in one line. Should I post a bug report, or a feature request?



Solution 1:[1]

In terms of why this would be a bad idea --

From the Zen of Python:

In the face of ambiguity, refuse the temptation to guess.

It's part of Python's design rationale to avoid ambiguity, and to force developers to choose explicitly what it is they want.

When you use from * import *, you're importing every name defined in every module. That means you're both running...

from lxml.etree.ElementTree import *

and

from xml.etree.ElementTree import *

...so, how are you to know if the function fromstring() you have in your namespace is from lxml.etree, or xml.etree, or some other library that isn't related to XML at all in the first place?

Similarly, this means you suddenly have a loads function, but you don't know if it's json.loads() or yaml.loads() or, again, something 100% unrelated.

This would make code both impossible to read and impossible to write.

Solution 2:[2]

In terms of why import *, from * import *, and other variants are not considered to be valid syntax in Python, that can be understood with a quick look at Python's grammar. The grammar for the import statement is

import_stmt     ::=  "import" module ["as" identifier] ("," module ["as" identifier])*
                     | "from" relative_module "import" identifier ["as" identifier] ("," identifier ["as" identifier])*
                     | "from" relative_module "import" "(" identifier ["as" identifier] ("," identifier ["as" identifier])* [","] ")"
                     | "from" relative_module "import" "*"
module          ::=  (identifier ".")* identifier
relative_module ::=  "."* module | "."+

You'll note that every token (aside from the literal text tokens) boils down to to some combination of identifier tokens. The grammar of identifiers is a bit more complicated, but a quick skim of the rules should make it clear that the character * (U+002A) isn't a valid identifier. This rules out constructs like import * since the grammar requires a valid identifier in the position where * appears. The only case where * is allowed in an import statement is when it's explicitly permitted as a literal text token. That only occurs in the "from" relative_module "import" "*" alternative.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2