Dynamic variable creation from string

Chris Angelico rosuav at gmail.com
Wed Dec 7 12:52:11 EST 2011


On Thu, Dec 8, 2011 at 4:09 AM, Massi <massi_srb at msn.com> wrote:
> def Sum(D) :
>    # Here some magic to create a,b,c from D
>    return a+b+c

Welcome to TMTOWTDI land! We do magic here... several different ways.

You _may_ be able to do this, which is roughly equivalent to the
extract() function in PHP:

locals().update(D)

However, this is NOT guaranteed to work. It's more likely to work with
globals(), but that wouldn't restrict the scope the way you asked.

One handy trick that I found on the internet while researching this:
Use (or abuse!) function keyword parameters to do the dictionary
extraction. You have to explicitly name your desired keys this way,
but it may be suitable. (The function doesn't have to be defined
inside the other, incidentally.)

>>> def Sum(D):
       def inner_sum(a,b,c,**kwargs):
               # Real logic goes here.
               return a+b+c
       return inner_sum(**D)

>>> a={"a":5,"b":10,"c":20}
>>> Sum(a)
35

Alternatively, the exec() and eval() functions can be given
dictionaries which will serve as their variable scopes, so you could
possibly use that. Definitely looking like ugly code though.

For something as trivial as Sum(), you'd do best to simply type
D['a']+D['b']+D['c'] and be done with it. For something where you're
going to use them a lot, probably easiest to be explicit:

a,b,c = D['a'],D['b'],D['c']

However, this violates DRY principle, and risks hard-to-trace mismatch
bugs. I'd be inclined to simply be explicit all the time.

Depending on what D is, you may actually want to consider rewriting
this as a class with a member function.

class whatever:
 def Sum(self):
   return self.a+self.b+self.c

There should be one obvious way to do it, says the zen of Python.
Frankly, I'm not sure what that one obvious way is, here, although I'm
pretty certain that several of the options posited would be very bad
for your code!

Still, down's very nice... They ARE alternative possibilities.

ChrisA



More information about the Python-list mailing list