Create a variable "on the fly"

Willem Broekema metawilm at gmail.com
Wed Jul 27 14:06:15 EDT 2005


Steve M:
> >>> locals()['OSCAR'] = 'the grouch'
> >>> OSCAR
> 'the grouch'
> >>>

Use "globals", not "locals":

  globals()['OSCAR'] = 'the grouch'

because <http://www.python.org/doc/current/lib/built-in-funcs.html>
states:

  locals()
  Update and 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.

Function globals() is not subject to this restriction.


- Willem




More information about the Python-list mailing list