[Tutor] Stupid bug
Steven D'Aprano
steve at pearwood.info
Thu Nov 11 18:33:20 CET 2010
Wayne Werner wrote:
> Including the sister bug - continually importing something and you still get
> the old function because you forgot to delete the .pyc file. Whoops!
Er, whoops is right... I think you may have misinterpreted what you were
seeing.
When you import a module for the first time, Python checks the date
stamps on the .pyc file (if it exists) and ONLY uses it if it is newer
than the .py file. If you update the source code, and then import the
module, the obsolete .pyc file will be ignored and over-ridden. You
don't have to delete the .pyc file in order for Python to use a newer
source file.
However, if the date stamps are screwed up, of course anything could
happen. Or if you move the .pyc files into an earlier part of the
PYTHONPATH, so they are seen before the .py files.
Note also that what I described only occurs the first time you import a
module. The second and subsequent time you import a module, it is not
retrieved from either the .py or the .pyc file, it is retrieved from the
cache in sys.modules.
Python is not really designed for reloading modules on the fly. There is
the reload() function (built-in in Python 2.x, moved into a library in
Python 3.x) but it is a fairly feeble thing, only good for the most
simple interactive use. Unless you're using a library that offers proper
reload functionality, the safest way to ensure you're using the latest
version of the module you've just edited is to exist the interpreter and
start it up again.
--
Steven
More information about the Tutor
mailing list