Safe to modify globals(), or not?
Elaine Jackson
elainejackson7355 at home.com
Sat Jan 31 01:17:18 EST 2004
Have you considered " globals()[name] = i " ?
"Josiah Carlson" <jcarlson at nospam.uci.edu> wrote in message
news:bvedh2$7h7$1 at news.service.uci.edu...
|
| >>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