Reloading modules
Michael Hudson
mwh at python.net
Thu Feb 21 07:02:08 EST 2002
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
Cheers,
M.
--
ARTHUR: But which is probably incapable of drinking the coffee.
-- The Hitch-Hikers Guide to the Galaxy, Episode 6
More information about the Python-list
mailing list