why import * only allowed at module level?

Cesar Douady cesar.douady at asim.lip6.fr
Mon Jan 14 11:28:54 CET 2002


In article <slrna44rdt.jaa.this at korppi.cs.tut.fi>, "Simo Salminen"
<this at is.invalid> wrote:

> * Hans Nowak [Mon, 14 Jan 2002 04:39:13 GMT]
>> "One side effect of the change is that the from module import * and
>> exec statements have been made illegal inside a function scope under
>> certain conditions. The Python reference manual has said all along that
>> from module import * is only legal at the top level of a module, but
>> the CPython interpreter has never enforced this before. As part of the
>> implementation of nested scopes, the compiler which turns Python source
>> into bytecodes has to generate different code to access variables in a
>> containing scope. from module import * and exec make it impossible for
>> the compiler to figure this out, because they add names to the local
>> namespace that are unknowable at compile time."
>> 
>> 
> [and that paragraph continues]
> "Therefore, if a function contains function definitions or lambda
> expressions with free variables, the compiler will flag this by raising
> a SyntaxError exception."
> 
> ok, but why:
>>>> def a1():
> ...     from os import *
> 
> does not work, but:
> 
>>>> def a2():
> ...     exec 'from os import *'
> 
> 
> works?
> 

As far as I know, from the compiler, the problem is the same : it does
not know what variable name is created.
Now the fact is that both form do work, but the import generates a
warning.
What does NOT work is :

def a():
	def b():
		x
	from os import *

or

def a():
	def b():
		x
	exec "whatever"

The reason is that Python does not know at compile time where to get x
from : this depends on whether the import or the exec defines it or not.
What seems curious to me is that in Hans' situation, the import generates
a warning while the exec does not.
What also is curious is that :

def a():
	def b():
		x
	exec "whatever" in globals(),locals()

is accepted but does not do
what you expect it to do : the local dict is not updated. For example :

def a():
	x=1
	exec "x=2" in globals(),locals()
	print x
a()

outputs "1" instead of "2", while :

def a():
	x=1
	exec "x=2"
	print x
a()

outputs "2", although the doc says that an unqualified exec is equivalent
to passing (globals(),locals()).

In my opinion, we are at the border of Python's semantic in a relatively
new area (nested scopes are new in 2.2) and Python is not yet mature
enough to be completely clean and simple.

Cesar.



More information about the Python-list mailing list