Why I need to declare import as global in function

Duncan Booth duncan.booth at invalid.invalid
Wed Nov 30 04:36:53 EST 2005


didier.doussaud at gmail.com wrote:

> I think I understand my problem, but first the sample code extracted to
> my project.
> 
> Rq : it's an automatic run of unitary test, the names of unitary test
> are parameter of main program "imported" file via the "execfile"
> function (an usage of "import" instead may be a solution....) :
> 
> file run.py :
> ----------------
> 
> def run_ut( test ) :
>     # to have the problem the execfile MUST be in a function
>     execfile( test )
> run_ut( "ut_00.py" )
> 
> 
> file ut_00.py :
> --------------------
> import math
> 
> def f() :
>     ## global math # <-- just decomment this line to avoid error
>     print "Second access :"
>     print "\t",math.pi # ERROR
> 
> print "First access :"
> print "\t",math.pi # OK
> f()
> 

How interesting. Can anyone actually explain the behaviour here?

Without the global statement everything works as I expect: the 'import 
math' is executed in the local scope of run_ut, so the function f() doesn't 
find it either in its local scope nor in global scope.

Inserting 'global math' at the outer level in ut_00.py (e.g. before the 
'import math') also works as I expect: math now becomes a global variable 
and is visible to f().

What I really don't understand is why the global statement *inside* f 
affects the scope of math outside f. If we had nested functions then a 
global variable in an inner function doesn't affect scope in outer 
functions. I realise that f() here isn't a nested function, but even so it 
looks to me like a bug unless I'm missing something.

(Technically the program is invoking undefined behaviour as the language 
reference says that names listed in a global statement must not be defined 
in an import statement, but that isn't really relevant since you can 
replace the import with an assignment statement and get the same weird 
behaviour.)



More information about the Python-list mailing list