Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "from ... import *" in a function not allowed?

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 a SyntaxError.

Why? What's the sense of avoiding to use it in a function? What's the problem?

like image 220
zer0uno Avatar asked Jan 22 '15 16:01

zer0uno


1 Answers

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.

like image 146
Sven Marnach Avatar answered Sep 20 '22 04:09

Sven Marnach