magic tricks

Jp Calderone exarkun at intarweb.us
Fri Jun 6 20:52:24 CEST 2003


On Fri, Jun 06, 2003 at 11:41:53AM -0700, Michele Simionato wrote:
> #<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) ? 
> 
  This doesn't work as soon as you call change.a() from a frame where
globals() is not locals().

> 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 ;-)
> 

  One approach:

    import bar

    xGlobal = None

    def foo():
      xGlobal = bar.changeMyGlobal()

  Another is to simply -not- use globals that way.

    class FooStash:
        x = None

    def foo(stash):
        bar.changeMyStash(stash)

    def main():
        stash = FooStash()
        foo(stash)

  Hope this helps,

  Jp

-- 
"There is no reason for any individual to have a computer in their
home."
                -- Ken Olson, President of DEC, World Future Society
                   Convention, 1977





More information about the Python-list mailing list