Fun with sys.modules

Roger Upole rupole at compaq.net
Mon Jun 12 17:35:55 EDT 2000


How about b=a ?
         Roger Upole

"Duncan Grisby" <dgrisby at uk.research.att.com> wrote in message
news:8i37m7$t96$1 at pegasus.csx.cam.ac.uk...
> I'm attempting to make a module appear under two different names, and
> I've come up with the following. It does what I want, but I'm a bit
> worried by one of the side effects...
>
> # a.py
> print "a started"
> answer = 42
>
> -------
>
> # b.py
> print "b started"
> answer = 1234
>
> # Now the evil bit
> import sys, a
> sys.modules["b"] = sys.modules["a"]
>
> # This is what worries me
> print "sys is", sys
> print "answer is", answer
>
> print "b finished"
>
> -------
>
> $ python
> Python 1.5.2 (#1, Feb  1 2000, 16:32:16)
>  [GCC egcs-2.91.66 19990314/Linux (egcs- on linux-i386
> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
> >>> import b
> b started
> a started
> sys is None
> answer is None
> b finished
>
>
> What happened to the globals in the running module!?  Presumably the
> entry in sys.modules was the only reference to module b, so it was
> deleted while it was still running. Is this safe?  My guess is that
> it's OK since it's basically the same situation as destructors which
> run after a module has been deleted.
>
> Any comments?  Am I totally crazy to be considering this?  If it is
> safe at the moment, what are the chances that a future Python release
> will behave differently?
>
> Cheers,
>
> Duncan.
>
> --
>  -- Duncan Grisby  \  Research Engineer  --
>   -- AT&T Laboratories Cambridge          --
>    -- http://www.uk.research.att.com/~dpg1 --





More information about the Python-list mailing list