Dynamic variable creation from string

Ethan Furman ethan at stoneleaf.us
Fri Dec 9 15:01:01 EST 2011


Massi wrote:
> Thank you all for your replies, first of all my Sum function was an
> example simplifying what I have to do in my real funciton. In general
> the D dictionary is complex, with a lot of keys, so I was searching
> for a quick method to access all the variables in it without doing the
> explicit creation:
> 
> a, b, c = D['a'], D['b'], D['c']
> 
> and without using directly the D dictionary (boring...).
> When I talked about nested function I meant both cases Chris, but this
> is not a really tighten bound.
> I tried to follow the hints of Chris together with some help by google
> and used the following code:
> 
> for k in D : exec "%s = D[k]" %k
> 
> That seems to do the trick, but someone speaks about "dirty code", can
> anyone point me out which problems this can generate?
> Again, thank you for your help!

Besides the serious security issues, this method won't make the problem 
any better in Python 3.

~Ethan~



More information about the Python-list mailing list