Dynamic variable creation from string
Terry Reedy
tjreedy at udel.edu
Wed Dec 7 17:59:33 EST 2011
On 12/7/2011 12:09 PM, Massi wrote:
> in my script I have a dictionary whose items are couples in the form
> (string, integer values), say
>
> D = {'a':1, 'b':2, 'c':3}
>
> This dictionary is passed to a function as a parameter, e.g. :
>
> 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
No. The set of local names for a function is determined when the
definition is executed and the body is compiled. Python 2 had an
exception -- 'from x import *' -- that required an alternate
complilation pathway. That possibility was eliminated in Python 3 and is
now a syntax error.
Within functions, 'locals().update(D)' is more or less guaranteed to
*not* add local names to the local namespace, even if it does add keys
to the locals() dict that shadows the local namespace.
> 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.
Local names, by definition, are lexically scoped to the function
definition and are not visible without. Since nested definitions are
part of that lexical scope, local names are always visible within nested
definitions. You cannot stop that. The association of local names is
usually dynamically limited to one function call. The two exceptions are
enclosure by a nested function that survives the function call and
generators in a paused state.
--
Terry Jan Reedy
More information about the Python-list
mailing list