NameError: global name 'btn_Matlab' is not defined ?

Stef Mientki stef.mientki at gmail.com
Wed Dec 29 04:27:40 EST 2010


On 28-12-2010 15:15, Steven D'Aprano wrote:
> On Tue, 28 Dec 2010 14:34:19 +0100, Stef Mientki wrote:
>
>> hello,
>>
>> Never seen this before and I've no explanation whatsoever (Python 2.6)
>>
>> I've some dynamic generated code,
>> one of objects generated is a wx.Button, called 'btn_Matlab'.
> How do you generate the code?
>
> What code is generated? What does it do?
>
>
>> After the code is generated, I can see that the button is created in the
>> local namespace
>>  
>>    print locals()['btn_Matlab']
>>
>> <wx._controls.Button; proxy of <Swig Object of type 'wxButton *' at
>> 0x3602d28> >
>>
>> but if I try to print the button (at exactly the same location), I get
>> an error
>>
>>     print btn_Matlab
>>
>> NameError: global name 'btn_Matlab' is not defined ?
>>
>> Why isn't the compiler first checking the local namespace ? any clues ?
>
> My guess is that you've declared btn_Matlab as global, and then 
> dynamically created a local with the same name using exec or similar.

thanks Stevem,

I found a solution.
I indeed tried to "inject" local variables from a stack a few levels deeper,
which doesn't seem to be possible (or reliable).
The documentation isn't overwhelming about that point, exec and eval doesn't mention anything,
but execfile warms for this issue.
The code now looks something like this:

      self.p_locals  = sys._getframe ( StackUp ).f_locals
      self.p_globals = sys._getframe ( StackUp ).f_globals

      Component = eval ( defi[1], self.p_globals, self.p_locals ) ( Parent, **Extra )

      self.p_globals[ 'Component' ] = Component
      if 'self' in defi[0] :
        exec ( '%s = Component' %( defi[0] ), self.p_globals, self.p_locals )
      else :
        exec ( '%s = Component' %( defi[0] ), self.p_globals)

cheers,
Stef




More information about the Python-list mailing list