Dynamic variable creation from string
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Dec 7 19:03:36 EST 2011
On Wed, 07 Dec 2011 09:09:16 -0800, Massi wrote:
> Is there a way to create three variables dynamically inside Sum in order
> to re write the function like this?
>
> def Sum(D) :
> # Here some magic to create a,b,c from D
> return a+b+c
No magic is needed.
a, b, c = D['a'], D['b'], D['c']
However, there is no way to create variables from an *arbitrary* set of
keys. And a good thing too, because how could you use them?
def Sum(D):
# Magic happens here
return a + b + z + foo + spam + fred + ... ???
Since you don't know what variable names will be created, you don't know
which variables you need to add. Dynamic creation of variables is ALMOST
ALWAYS the wrong approach.
In this specific case, what you should do to add up an arbitrary number
of values from a dict is:
sum(D.values())
> It is really important that the scope of a,b,c is limited to the Sum
> function, they must not exisit outside it or inside any other nested
> functions.
The first part is trivially easy; since you are assigning to local
variables, by definition they will be local to the Sum function and will
not exist outside it.
The second part is impossible, because that is not how Python works.
Nested functions in Python can always see variables in their enclosing
scope. If you don't want that behaviour, use another language, or don't
use nested functions.
--
Steven
More information about the Python-list
mailing list