Problem with reimporting modules

Dustan DustanGroups at gmail.com
Sun Feb 11 10:51:51 EST 2007


On Feb 11, 5:53 am, Christoph Zwerschke <c... at online.de> wrote:
> I'm currently investigating a problem that can hit you in TurboGears
> when Kid template modules are reloaded in the background, because in
> certain situations, global variables suddenly are set to None values.
>
> I tracked it down to the following behavior of Python. Assume you have a
> module hello.py like that:
>
> ---- hello. py ----
> greeting = 'Hello!'
> def print_hello():
>      print greeting
> -------------------
>
> Now run the following code:
>
> from hello import print_hello
> print_hello()
> import sys
> del sys.modules['hello'] # delete module
> import hello # recreate module
> print_hello()
>
> The second print_hello() prints "None" instead of "Hello!". Why is that?
> I had expected that it either prints an error or print "Hello!" as well.
>
> Is this intended behavior of Python?
>
> -- Christoph

You're most likely looking for reload:
http://docs.python.org/lib/built-in-funcs.html#l2h-61
The documentation does imply that deleting a module from sys.modules
may not be what you want:
http://docs.python.org/lib/module-sys.html#l2h-5147

>>> import sys
>>> import warnings as previous_warnings # for example
>>> # testing whether reload returns the same module object:
... reload(previous_warnings) is previous_warnings
True
>>> # the following result is rather intuitive, but for
... # the sake of demonstration, I'll do it anyway.
... del sys.modules['warnings']
>>> import warnings as after_warnings
>>> after_warnings is previous_warnings
False




More information about the Python-list mailing list