eval, exec and execfile dilemma

Laszlo Nagy gandalf at shopzeus.com
Sat Jul 30 18:18:51 EDT 2011


>> UnboundLocalError: local variable 'bar' referenced before assignment
>
> This works, though (at least it does on 2.7):
>
> --> exec "def foo():\n\tglobal bar\n\tbar+=1\n\treturn 1\n"
> --> bar = 9
> --> foo()
> 1
> --> bar
> 10
>
> Laszlo, why do you think you can't use exec?
I'm sorry, first I was not aware of the "in globals locals" part.

Then I also got an UnboundLocalError. Then I also figured out that I can 
use "global bar", but I did not want to. Reason: 100 functions/second 
installed to global namespace doesn't sound well. However, now I 
discovered the locals parameter, and I figured out that I can force the 
compiler to treat the name of the function to be a local name. I do this 
by reserving its name in locals. Then the compiler has no choice but to 
place it in the local namespace:

locals = {'_f_':None}
globals ={} # More specialized version in my program...
exec "def _f_(a):\n\treturn a+1\n\n" in globals,locals
print locals['_f_'](4) # prints '5'

This is good because it is not interfering with module level globals(), 
nor the local namespace. Also good because I can restrict what is 
visible from inside the function.

Thank you for your help.

Best,

    Laszlo




More information about the Python-list mailing list