[Python-Dev] Is this a bug?

Josiah Carlson jcarlson at uci.edu
Wed Aug 9 17:59:30 CEST 2006


Georg Brandl <g.brandl at gmx.net> wrote:
> 
> Is this considered a bug? Sure, deleting modules from sys.modules
> isn't quite common, but it happened to me on one occasion.
> 
> Python 2.4.3 (#1, Jul 29 2006, 10:52:20)
>  >>> import logging
>  >>> import sys
>  >>> del logging
>  >>> del sys.modules['logging']
>  >>> ^D
> Error in atexit._run_exitfuncs:
> Traceback (most recent call last):
>    File "/usr/lib/python2.4/atexit.py", line 24, in _run_exitfuncs
>      func(*targs, **kargs)
>    File "/usr/lib/python2.4/logging/__init__.py", line 1328, in shutdown
>      for h in _handlerList[:]: # was _handlers.keys():
> TypeError: unsubscriptable object
> Error in sys.exitfunc:
> Traceback (most recent call last):
>    File "/usr/lib/python2.4/atexit.py", line 24, in _run_exitfuncs
>      func(*targs, **kargs)
>    File "/usr/lib/python2.4/logging/__init__.py", line 1328, in shutdown
>      for h in _handlerList[:]: # was _handlers.keys():
> TypeError: unsubscriptable object
> 
> Obviously, _handlerList (as a global) is already cleaned up, which is why
> the subscript fails.

Interestingly enough, I recently ran into a series of errors relating to
manipulating sys.modules and using imp.load_module...

The imp.load_module and the 3 other simple variants involved importing a
module 'x.y' without the package 'x' having been imported first.  This
resulted in all C-modules being re-initialized (builtins, 3rd party, etc.),
causing things like sys.stdout wrappers to be removed, and in the case
of wx, segfaults galore (especially during shutdown).  Python 2.3 and
2.4 performed these imports silently, while 2.5 complains "SystemError:
Parent module 'x' not loaded", which is actually a useful message, and
helped me fix it.


I have a use-case for replacing sys.modules['__main__'] with a different
module, and initial attempts to do:
    sys.modules['__main__'] = other_module
    other_module.main()

Resulted in:
    AttributeError: 'NoneType' object has no attribute 'main'

This is the case for Python 2.3, 2.4, and 2.5 beta.  prefixing the above
two operations with:
    sys.modules['_oldmain'] = sys.modules['__main__']

Is sufficient to prevent Python from tearing down everything after the
sys.modules['__main__'] reassignment.  Not a big deal, but a sys.modules
manipulation that has a gotcha.

 - Josiah



More information about the Python-Dev mailing list