Reloading modules

Bengt Richter bokr at oz.net
Fri Feb 22 15:52:33 EST 2002


On Thu, 21 Feb 2002 12:02:08 GMT, Michael Hudson <mwh at python.net> wrote:

>Michael Hudson <mwh at python.net> writes:
>
>> Jeff Davis <jdavis at empires.org> writes:
>> 
>> > Is there a way to say that all calls to import should check for a newer 
>> > version, if a newer one exists then completely drop the old one and import 
>> > the new one?
>> 
>> An import hook could do this.  Wouldn't be trivial to write, but not
>> too hard, either.
>
>This "seems to work".  It's probably still a bit fragile, but might be
>handy during development, I guess.
>
>import __builtin__, os, time
>
>old_import = __import__
>
>def my_import(*args):
>    mod = old_import(*args)
>    file = getattr(mod, "__file__", "")
>    if file.endswith("c"):
>        file = file[:-1]
>    if not file.endswith(".py"):
>        return mod
>    mtime = os.path.getmtime(mod.__file__[:-1])
>    itime = getattr(mod, "__importtime__", 0)
>    if itime < mtime:
>        reload(mod)
>    mod.__importtime__ = time.time()
>    return mod
>
>__builtin__.__import__ = my_import
>
In general, I'd be wary of using time() and getmtime() to detect file changes
programmatically if there's the faintest chance of a change happening in
less than two seconds (the file time stamp resolution of, e.g., Windows 95).

You can sometimes get bit even in a fast IDE edit-build situation.

Slower, but reliable, might be to check an md5 digest of the file for change.
Of course, then you could not expect to trigger this with touch.

Regards,
Bengt Richter




More information about the Python-list mailing list