Python pyc cache is not invalidated when source code is modified quickly

1 day ago 3
ARTICLE AD BOX

I am writing a Python project where the source code is modified quickly. I am noticing that Python seems to run old versions of the program.

a.py:

import b print(b.i)

b.py:

# will be changed later i = 0

c.sh:

for i in {1..20}; do echo "i = $i" > b.py sleep 0.3 echo -n "$i " python3 a.py done

When I run c.sh, I see:

$ bash c.sh 1 1 2 1 3 1 4 4 5 4 6 4 7 7 8 7 9 7 10 10 11 10 12 10 13 13 14 13 15 13 16 16 17 16 18 16 19 19 20 19 $

I read https://docs.python.org/3/reference/import.html#cached-bytecode-invalidation. It seems that Python invalidates .pyc files based on time. And it appears that on my system the accuracy of the time is 1 second. I am using Linux (Debian 13), Python 3.13.5.

Is this a bug in Python? If not, how should I modify my project?

I tried python3 --check-hash-based-pycs always a.py, it does not work. python3 -B a.py works, but I wonder whether there are other ways to workaround this problem.

Read Entire Article