pyc file [Newbie Question]

Peter Otten __peter__ at web.de
Tue Apr 3 03:44:43 EDT 2007


Jim Aikin wrote:

> Just starting to learn Python and going through the Tutorial in the Help
> file. FWIW, I'm a hobbyist programmer -- not extremely knowledgeable, but
> not entirely clueless.
> 
> In 6.1.2 of the Tutorial, I find this: "The modification time of the
> version of spam.py used to create spam.pyc is recorded in spam.pyc, and
> the .pyc file is ignored if these don't match." Either I don't understand
> this, or it isn't correct.

$ echo 'print "Hello, Jim"' > tmp.py
$ python -c'import tmp'
Hello, Jim

Now let's change tmp.pyc in a way that we can see but Python won't notice:

$ python -c's = open("tmp.pyc").read(); open("tmp.pyc",
"w").write(s.replace("Jim", "JIM"))'
$ python -c'import tmp'
Hello, JIM

As you can see, tmp.pyc is not recreated. But if we change the timestamp of
tmp.py

$ touch tmp.py
$ python -c'import tmp'
Hello, Jim

it is. As Steven says, the behaviour you experience is caused by the module
cache. That is, a module "my_module" is only imported once per session, no
matter how many 'import my_module' statements you have in your application:

$ python -c'import tmp; import tmp'
Hello, Jim

That is why the greeting above is printed only once, and why your changes
don't have any immediate effect.

Peter



More information about the Python-list mailing list