[Numpy-discussion] exec: bad practice?

Rick White rlw@stsci....
Tue Sep 15 09:30:43 CDT 2009


You're not supposed to write to the locals() dictionary.  Sometimes  
it works, but sometimes it doesn't.  From the Python library docs:

locals()
	Update and return a dictionary representing the current local symbol  
table.
	Note: The contents of this dictionary should not be modified;  
changes may not affect the values of local variables used by the  
interpreter.

I think the only way to create a variable with a program-specified  
name in the local namespace is to use exec (but I'd be happy to be  
corrected).

Cheers,
Rick

On Sep 15, 2009 Sebastien Binet wrote:

> hi John,
>
>> I have a bit of code where I create arrays with meaningful names via:
>>
>> meat = ['beef','lamb','pork']
>> cut = ['ribs','cutlets']
>>
>> for m in meat:
>>    for c in cut:
>>          exec("consumed_%s_%s = np.zeros 
>> ((numxgrid,numygrid,nummeasured))"
>>  % (m,c))
>>
>> Is this 'pythonic'? Or is it bad practice (and potentially slow)  
>> to use the
>> 'exec' statement?
>
> usage of the exec statement is usually frown upon and can be side  
> stepped.
> e.g:
>
> for m in meat:
>     for c in cut:
>       locals()['consumed_%s_%s' % (m,c)] = some_array
>
> hth,
> sebastien.



More information about the NumPy-Discussion mailing list