local variable not found

holger krekel pyth at devel.trillke.net
Sat Apr 27 17:20:19 EDT 2002


On Sat, Apr 27, 2002 at 11:01:32PM +0200, Alain Tesio wrote:
> Hi,
> 
> I have a problem trying to use code compiled on the fly,
> python looks in the globals variables only.
> 
> Look at this example :
> 
> ===
> import codeop
> 
> def f():
> 	x=[1,2,3]
> 	eval(codeop.compile_command("y=x"))
> 	print y
> 
> f()

You have the same problem that i had (see the 10-minute
old thread about 'update locals()'.

Problem is that when python compiles your function
it doesn't look into the string, that's done at runtime.
Thats why 'print y' is assumed to refer to a global variable.

Now when you do 

> 	eval(codeop.compile_command("y=x"))

the assignment is made in your local scope.
This results in 

> NameError: global name 'y' is not defined

so much for the problem :-)

    holger





More information about the Python-list mailing list