Reloading a module

Jeff Epler jepler at unpythonic.net
Mon Sep 30 23:03:57 EDT 2002


On Tue, Oct 01, 2002 at 02:16:15AM +0000, Tom wrote:
> I wish it were that simple. I've used reload(module) many times, each 
> time hoping that it would do what the documentation says it will do. 
> I've tested it by adding a simple variable to my module, watching to see 
> if it shows up in the new import, but it never does. I noticed also that 
> sometimes it reloads from the .pyc file, and if the reload happens 
> before the .pyc file is updated with the new changes, the changes won't 
> be available. Even if I force a reload from the updated .py file by 
> deleting .pyc file, it still retains the old code. I'm at a loss to 
> understand what's going on.

# silly.py
print "That's silly -- and a bit suspect, I think"

    Python 2.3a0 (#1, Jul 13 2002, 09:27:09) 
    [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import silly
    That's silly -- and a bit suspect, I think
    >>>

(editing the file:
# silly.py
print "spam spam spam spam spam"
)
    >>> reload(silly)
    spam spam spam spam spam
    <module 'silly' from 'silly.py'>
    >>>

As for .pyc vs .py, Python follows these steps when importing a module:
    if a .pyc file exists, read the magic number, version, and the
	stored timestamp.  Compare the version to this Python version,
	and the stored timestamp to the .py file's timestamp.  If these
	both match, or the version matches and the .py file doesn't exist,
	use the .pyc file.
    otherwise, compile the .py file and rebuild the .pyc file along the way

The only circumstance that would interfere with this is NFS or another
network filesystem making the check of the timestamp on the .py file
unreliable---i.e., python can fail to detect that the .py file has been
updated, because the OS gives it stale data.  Using a filesystem that has
no timestamp at all (or a very granular timestamp, so that two revisions of
"silly.py" could share the same timestamp) could cause the same problem,
though I don't know of any such filesystems offhand.

(That said, I rarely actually notice problems of this type over NFS)

It's possible that you've discovered some sort of new problem with the way
.pyc caching or reloading work, but the idea is so simple that I can't see it
failing...

Jeff




More information about the Python-list mailing list