magic tricks

Michele Simionato mis6 at pitt.edu
Fri Jun 6 20:41:53 CEST 2003


#<change.py>

import sys
callerglobals=sys._getframe(1).f_globals

def a(x):
    callerglobals['a']=x

#</change.py>

>>> import change
>>> a=1
>>> change.a(2)
>>> a
2

This works, but the standard library explicitely warns AGAINT this kind 
of magic tricks. Thus my question: what's the safe way of doing this 
(BTW, what can go wrong with sys._getframe approach) ? 

In other words, I want to change a global variable of a given module by 
invoking a different module (and I know this is not a Good Thing ;-)


                               Michele




More information about the Python-list mailing list