rm -rf __pycache__ *.pyc *.pyo
cat >mymodule.py <<EOM
def greet():
assert False
EOM
cat >main.py <<EOM
import mymodule
mymodule.greet()
EOM
python -OO -m py_compile mymodule.py
strace python main.py 2>&1 | grep mymodule
You will be surprised that pyo is not used.
openat(AT_FDCWD, "/home/devel/python_compile_test/mymodule.pyc", O_RDONLY) = -1 ENOENT (No such file or directory)
unlink("/home/devel/python_compile_test/mymodule.pyc") = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/home/devel/python_compile_test/mymodule.pyc", O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0100644) = 4
Meanwhile these works:
python -m py_compile mymodule.py
strace python main.py 2>&1 | grep mymodule
python -OO -m py_compile mymodule.py
strace python -OO main.py 2>&1 | grep mymodule
This is reproducible on both Python2 and Python3.
This means that pycache's optimization level and python running optimization level must be the same.