I knew that a .pyc
file is generated by the python interpreter and contains the byte code as this question said.
I thought python interpreter is using the time stamp to detect whether a .pyc
is newer than a .py
, and if it is, skipped compiling it again when executing. (The way what makefile do)
So, I did a test, but it seemed I was wrong.
- I wrote
t.py
containsprint '123'
andt1.py
containsimport t
. Running commandpython t1.py
gave the output123
and generatedt.pyc
, all as expected. - Then I edited
t.py
asprint '1234'
and updated the time stamp oft.pyc
by usingtouch t.pyc
. - Run
python t1.py
again, I thought I would get123
but1234
indeed. So it seemed the python interpreter still knew thatt.py
is updated.
Then I wondered whether python interpreter will compile and generate t.pyc
every time running python t1.py
. But when I run python t1.py
several times, I found that the t.pyc
will not be updated when t.py
is not updated.
So, my question is: how python interpreter knows when to compile and update a .pyc
file?
Updated
Since python interpreter is using the timestamp stored in the .pyc
file. I think it a record of when .pyc
was last updated. And when imported, compare it with the timestamp of .py
file.
So I tried to hack it in this way: change the OS time to an older one, and edit .py
file.
I thought when imported again, the .py
seems older than the .pyc
, and the python interpreter will not update .pyc
. But I was wrong again.
So, does the python interpreter compare these two timestamp not in a older or newer way but in a exactly equal way?
In a exectly equal way, I means the timestamp in .pyc
records the when the .py
was last modified. When imported, it compares the timestamp with the current timestamp of .py
, if it's not the same, recompile and update .pyc
.