From the documentation:
The wild card form of import —
from module import *
— is only allowed at the module level. Attempting to use it in class or function definitions will raise aSyntaxError
.
Why? What's the sense of avoiding to use it in a function? What's the problem?
The CPython implementation uses a special optimisation for local variables: They aren't dynamically looked up at runtime from a dictionary, as globals are, but rather are assigned indices statically at compile time, and are looked up by index at runtime, which is a lot faster. This requires the Python compiler to be able to identify all local names at compile time, which is impossible if you have a wildcard import at function level.
In Python 2, there was still a fallback mechanism that got invoked in cases where it wasn't always possible to determine all local names statically. This mechanism used a dynamic dictionary for local variables, significantly slowing down execution.
For example this code
def f():
exec "x = 2"
print x
works as expected in Python 2, whereas
def f():
exec("x = 2")
print(x)
results in a NameError
in Python 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With