Dynamic variable creation from string

Waldek M. wm at localhost.localdomain
Wed Dec 7 12:46:07 EST 2011


On Wed, 7 Dec 2011 09:09:16 -0800 (PST), Massi wrote:
> def Sum(D) :
>     return D['a']+D['b']+D['c']
> 
> 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

Hello,

> 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.
> Thanks in advance for your help!

Can you clarify a bit? I'm not sure why do you need to define any
additional variables at all. You do not return variables
from a function - you can return *a value* which may be
a simple type or complex type.

Or maybe you mean something like creating a global name
from inside of a function? Well, that doesn't sound like a good idea,
though...

>>> def foo():
	global a
	a = 5
	
>>> foo()
>>> print("The variable is: ", a)
The variable is:  5
>>> 



Best regards,
Waldek



More information about the Python-list mailing list