Unexpected side-effects of assigning to sys.modules[__name__]

  • Thread starter Steven D'Aprano
  • Start date
S

Steven D'Aprano

Given this module:

#funny.py
import sys
print "Before:"
print " __name__ =", __name__
print " sys.modules[__name__] =", sys.modules[__name__]
sys.modules[__name__] = 123
print "After:"
print " __name__ =", __name__
print " sys =", sys


when I run it I get these results:


[steve@sylar python]$ python2.6 funny.py
Before:
__name__ = __main__
sys.modules[__name__] = <module '__main__' from 'funny.py'>
After:
__name__ = None
sys = None



I'm completely perplexed by this behaviour. sys.modules() seems to be a
regular dict, at least according to type(), and yet assigning to an item
of it seems to have unexpected, and rather weird, side-effects.

What am I missing?
 
J

Jean-Michel Pichavant

Steven said:
Given this module:

#funny.py
import sys
print "Before:"
print " __name__ =", __name__
print " sys.modules[__name__] =", sys.modules[__name__]
sys.modules[__name__] = 123
print "After:"
print " __name__ =", __name__
print " sys =", sys


when I run it I get these results:


[steve@sylar python]$ python2.6 funny.py
Before:
__name__ = __main__
sys.modules[__name__] = <module '__main__' from 'funny.py'>
After:
__name__ = None
sys = None



I'm completely perplexed by this behaviour. sys.modules() seems to be a
regular dict, at least according to type(), and yet assigning to an item
of it seems to have unexpected, and rather weird, side-effects.

What am I missing?
Maybe when you assign 123 to sys.modules[__name__], you've removed the
last reference on <module '__main__' from 'funny.py'> and it is
garbaged. You are then loosing all your initial namespace.


try this one:
#funny.py
import sys
print "Before:"
print " __name__ =", __name__
print " sys.modules[__name__] =", sys.modules[__name__]
foo = sys.modules[__name__] # backup ref for the garbage collector
sys.modules[__name__] = 123
print "After:"
print " __name__ =", __name__
print " sys =", sys

Jean-Michel
 
S

Steven D'Aprano

I'm completely perplexed by this behaviour. sys.modules() seems to be
a regular dict, at least according to type(), and yet assigning to an
item of it seems to have unexpected, and rather weird, side-effects.

What am I missing?
Maybe when you assign 123 to sys.modules[__name__], you've removed the
last reference on <module '__main__' from 'funny.py'> and it is
garbaged. You are then loosing all your initial namespace.

By Jove, I think you've got it! How obvious in hindsight. Thank you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,228
Latest member
MikeMichal

Latest Threads

Top