Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write-import-call same Python module multiple times runs outdated code

import sys
import os
import time

MODULE_NAME = "mycode"


def write_module(version):
    with open(MODULE_NAME+".py", "w") as f:
        f.write("def fun():"+os.linesep)
        f.write("    print('Code version:',"+str(version)+")")


for i in range(5):
    # WRITE A PYTHON FILE AUTOMATICALLY
    write_module(i)

    # IMPORT IT
    if MODULE_NAME in sys.modules:
        del sys.modules[MODULE_NAME]
    # time.sleep(1)  # <------------------------ WHY IS IT MANDATORY ????
    module = __import__(MODULE_NAME)
    fun = module.fun

    # CALL IT
    fun()

Produces:

Code version: 0
Code version: 0
Code version: 0
Code version: 0
Code version: 0

I expected:

Code version: 0
Code version: 1
Code version: 2
Code version: 3
Code version: 4

I am developing Python code, writing Python code automatically. Python import instructions do not work as I expected. It looks like an asynchronous callback.

I don't know why, adding the line time.sleep(1) corrects the error.

like image 966
Pierrick Pochelu Avatar asked Sep 16 '26 17:09

Pierrick Pochelu


1 Answers

The source bytes are cached in __pycache__ directory. _validate_timestamp_pyc validates it against the source last-modified time — same without time.sleep(1) — and the source size.

You can remove the pyc file before deleting the module from sys.modules.

    if MODULE_NAME in sys.modules:
        os.remove(sys.modules[MODULE_NAME].__cached__)  # Add this
        del sys.modules[MODULE_NAME]
like image 114
aaron Avatar answered Sep 18 '26 08:09

aaron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!