Creating a local variable with a parameterized name

Justin Sheehy dworkin at ccs.neu.edu
Sat Jan 29 21:54:37 EST 2000


Nic Williams <nic at csee.uq.edu.au> writes:

> Michael if you really need to insert the variable into the local name
> space then be aware of the built-in functions global() and locals()
> which return dictionaries holding the global and local symbol tables,
> respectively. There is also vars([object]) which gives an object's
> symbol table or (when no parameter is given) the local symbol table.
> 
> The result isn't much more attractive than Justin's but you do insert
> the variable into the 'official' local space:
> 
> def f(name):
> 	locals()[name]=123
> 	print locals()[name]

This is why I didn't recommend that approach, from the Python documentation:

locals () 
       Return a dictionary representing the current local symbol table. 
       Warning: the contents of this dictionary should not be modified; 
       changes may not affect the values of local variables used by 
       the interpreter. 

Yes, I know that it works right now, but it is also quite clearly
marked as something which could stop working without warning in a
future version of Python.

If you must recommend something like that, it is only polite to point
out that it is strictly incorrect code and should not be relied upon.

-Justin

 




More information about the Python-list mailing list