Caching in Modules in Python3

Viewed 7

While importing modules in a program a single module is only loaded once and then accessed from sys.modules dictionary. And also when a module is first run a .pyc file is created. Does the former make use of the latter or are they unrelated?

1 Answers

They are unrelated.

The .pyc file is a cached file of the compiled byte code for the script/application. Since Python does this every time a script is run it keeps it cached until the original .py file is modified and run again in which case the compiler will run again. This reduces the time of successive startups of the same unmodified script/application as the compiled byte code is already cached. It's quite helpful when running something over and over again but it only runs for a short while.

Related