Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #10602

Re: eval, exec and execfile dilemma

Date 2011-07-31 00:18 +0200
From Laszlo Nagy <gandalf@shopzeus.com>
Subject Re: eval, exec and execfile dilemma
References <4E346028.5000302@shopzeus.com> <CAPTjJmpitXU6mFH1C32=f8CSzL-oDZpx-jNxb0UZAcCZqDtq8A@mail.gmail.com> <4E34761C.7030609@stoneleaf.us>
Newsgroups comp.lang.python
Message-ID <mailman.1677.1312064338.1164.python-list@python.org> (permalink)

Show all headers | View raw


>> 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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: eval, exec and execfile dilemma Laszlo Nagy <gandalf@shopzeus.com> - 2011-07-31 00:18 +0200
  Re: eval, exec and execfile dilemma Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-31 09:31 +1000
    Re: eval, exec and execfile dilemma Laszlo Nagy <gandalf@shopzeus.com> - 2011-07-31 12:21 +0200

csiph-web