As a follow-up to this question, I have a new question:
What is happening internally in os.remove(module_name)
and del sys.modules["module_name"]
?
I need an urgent help for this.Please help me out.
As a follow-up to this question, I have a new question:
What is happening internally in os.remove(module_name)
and del sys.modules["module_name"]
?
I need an urgent help for this.Please help me out.
The short answer is that os.remove(module_name)
will remove a file from the filesystem. del sys.modules["module_name"]
will remove a module from the cache of previously loaded modules that the current Python interpreter is maintaining.
In Python, when you import a module, the interpreter checks to see if there is a .pyc
file of the same name as the .py
file you are trying to import. If there is, and if the .py
file has not changed since the .pyc
file has been imported, then Python will load the .pyc
file (which is significantly faster).
If the .pyc
file does not exist, or the .py
file has been changed since the .pyc
file was created, then the .py
file is loaded and a new .pyc
file is created. (It is worth noting that simply running a Python file, say test.py
will not cause a test.pyc
to be created. Only import
ing modules causes this to happen.)
sys.modules
is another matter entirely. In order to speed up code which imports the same module twice, Python maintains a list of the modules that have been imported during the current interpreter session. If the module being imported is in sys.modules
, then the cached version will be read (neither .py
nor .pyc
files will be checked for on the disk). Python provides a builtin function reload()
which allows you to bypass the module cache and force a reload from disk.
To get more information on Python's module system, see the docs on modules.
my oneliner for this job:
find . -name *.pyc |xargs rm
NB: You need Linux (or Unix-like OS)
I start a lot of apps like this
import os
os.system('attrib +H *.pyc /S')
On windows this hides any visible compiled files when the app starts - they give me the pips.