faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

8 of 9 people (89%) answered Yes
Recently 7 of 8 people (88%) answered Yes

Entry

Unloading modules (was: Developing and testing modules live)

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 256, Peter Sommerfeld


"""
Packages: modules_and_packages
"""
"""
> When I develop modules, I prefer testing them immediately after I
> write each specific function. One solution I've tried is to run an
> instance of the Python interpreter in a shell buffer alongside my
> editting in another. When I import the module, test some
> functionality and modify the source file, I've discovered that del'ing
> and re-importing the module doesn't include the changes. For example,
> if I write:
> 
> print "Hello, world."
> 
> in test.py and import test, I receive the message. If I modify the
> message to just "Hello.", delete test and re-import it, it doesn't
> even print the message.
> 
> To me, deleting and re-importing seemed to be an intuitous way of
> reloading my changes, but I seem to be missing some important fact
> about how importing works. Granted, I can kill the interpreter and
> restart it, but this is a bit slower. Is there a way to quickly reread
> the module without restarting?
I usually have on top of my __main__ module this code:
"""
def unload(*args):
    #
    from string import split, join
    from sys import modules
    #
    for name in args:
        for module in modules.keys():
            s = split(module, ".")
            if s[0] == name:
                s = join(s,".")
                del modules[s]
# usage example:
"""
unload ("test1","test2")    # the modules of my current project
from test1 import *
from test2 import *
"""
"""
I don't need a second interpreter this way. It is assumed that the
unloaded modules aren't used by another part of the interpreter or
something will probably crash. Works well with MacIDE, probably on
Win/Unix too.
Hope this helps
Peter
"""