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

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Aug 6 19:39:10 CEST 2009

Given this module:

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 at sylar python]$ python2.6 funny.py
  __name__ = __main__
  sys.modules[__name__] = <module '__main__' from 'funny.py'>
  __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?


More information about the Python-list mailing list