Safe to modify globals(), or not?

Josiah Carlson jcarlson at nospam.uci.edu
Fri Jan 30 21:04:45 CET 2004


>>Fair enough. However, is there anything wrong with modifying globals()
> 
> 
> No.  "globals()['a'] = 3" is exactly the same as "a=3" executed at module
> scope, outside of functions.  The purpose is to allow you to set a variable
> whose name you do not know until runtime.  An example, as in your
> application, is when the name comes from user input.

I personally enjoy modifying globals() as it suits my needs.  Another 
statement that is quite useful is global.
 >>> def set_global_k(i):
...     global k
...     k = i
...
 >>> set_global_k(5)
 >>> k
5
 >>> set_global_k(6)
 >>> k
6
 >>>

Really only useful for when you know the name of the variable before 
runtime, but then again, one could always:
 >>> def set_global_name(i, name):
...     exec('global %s;%s = i'%(name, name))
...
 >>> set_global_name(10, 'l')
 >>> l
10


MMM, global manipulation.  Now if only there was a python function for 
global dominance, though perhaps globals().clear() is sufficient. 
Mua-hah-hah.

  - Josiah



More information about the Python-list mailing list