0

As has been well-documented (SO question here, Python import documentation, etc), python caches its imports and generates compiled .pyc files so that you only have to import files once. However, not all of the information is cached; I don't understand exactly how the caching works. I would like to more completely cache the imports so that files that take a long time to import can be sped up. For example, say I have these files, which look like this:

main.py
/src
    mysrc.py

main.py

import time
start = time.time()
from src.mysrc import TesterClass

print ("elapsed:", time.time() - start)

mysrc.py

import time
time.sleep(2)  # SLEEPING FOR 2 SECONDS HERE

class TesterClass:
    def __init__(self):
        pass

Then if I call main.py from the command line, it will show that just over 2 seconds elapses every time, no matter if the .pyc files have already been generated.
It seems like there would be a way to keep track of the class if it has already been imported, so that subsequent calls to import the class would be much quicker.
Is this possible?

tiberius
  • 430
  • 2
  • 14
  • Try importing TesterClass twice in main.py. Put some timing print functions before, in between and after the two imports. – 9769953 Jul 14 '22 at 17:03
  • Statements at module level are always executed. `time.sleep(2)` is at module level. – 9769953 Jul 14 '22 at 17:06
  • 1
    Note that byte-compiling a Python file does not mean executing it. `time.sleep(2)` is not executed during compilation to a `.pyc` file. – 9769953 Jul 14 '22 at 17:07

0 Answers0