Exec woes

Rhodri James rhodri at wildebst.demon.co.uk
Fri Jan 30 00:36:51 CET 2009


On Thu, 29 Jan 2009 08:15:57 -0000, Hendrik van Rooyen  
<mail at microcorp.co.za> wrote:

>  "Rhodri James" <rhodri at wildebst.demon.co.uk> wrote:
> To: <python-list at python.org>
> Sent: Thursday, January 29, 2009 6:12 AM
> Subject: Re: Exec woes
>
>
>> On Wed, 28 Jan 2009 07:47:00 -0000, Hendrik van Rooyen
>> <mail at mic,..p.co.za> wrote:
>
>> > This is actually not correct - it is the root cause of my trouble.
>> > if you write, in a nested scope:
>> >
>> > exec ( "somestring to execute" in globals(),locals())
>> >
>> > You get the syntax error, as the interpreter somehow sees it as one,
>> > unqualified thing.
>>
>> Well, no.  Look at the error Python gives you, nested scope or not:
>>
>> Traceback (most recent call last):
>>    File "<stdin>", line 1, in <module>
>> TypeError: exec: arg 1 must be a string, file, or code object
>>
>> If exec is a function, arg 1 is the boolean expression
>>    "somestring to execute" in globals()
>> which is unlikely to be what you want.  If exec is a statement,
>> arg 1 is a tuple of two elements,
>>    "somestring to execute" in globals()
>> and
>>    locals()
>> which is also unlikely to be what you want.  Neither of these are
>> giving you a string, file or code object, exactly as the interpreter
>> is telling you.
>
> Well, no - I stick by my assertion, about the nested scope:
>
>>>> def rubbish():
>  def deep_rubbish():
>   exec('BUILD = "somestring"' in globals(),locals())
>
> SyntaxError: unqualified exec is not allowed in function 'deep_rubbish'  
> it is a
> nested function (<pyshell#3>, line 3)
>>>>
>
> That is all I was saying - It was the brackets that buggered me,
> and adding the globals() and locals() inside the brackets, inside
> the nested scope, makes no difference - the interpreter sees it
> as an unqualified exec.

Correct.  In the language of the previous error message, the tuple
('BUILD = "something"' in globals(), locals()) is still the first
argument.

> Did you actually try it in a nested scope before asserting
> "nested scope or not" ?

Sorry, I assumed that you'd noticed that they were complaining
about the same thing.

> If you just do, in the outside scope, the thing I did originally:
>
>>>> exec('BUILD = "foobar"')
>>>> BUILD
> 'foobar'
>>>>
>
> Then the brackets are ignored, and the defaults kick in.

There are no commas, so the brackets are just fulfilling their
usual roll of overriding operator precedence.  Nothing strange
there.

There really is nothing unusual at all going on here.  Please
don't get the idea that brackets do anything unusual with an exec,
or any other Python statement for that matter.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list