r/learnpython • u/michalesco • May 19 '17
Sometimes I see Python creates __pycache__ folder, sometimes not. Why?
Recently I've noticed that a new folder appeared in my coding project. Its name is __pycache__. I have never noticed anything like that.
Why does Python create it? Does it have any special meaning? Why doesn't Python create it whenever I write a new script? How does it work?
Thank you very much.
7
u/Rhomboid May 19 '17
When you import a module, Python stores the compiled bytecode in that directory so that future imports can use it directly, rather than having to parse and compile the source again. It does not do that for merely running a script, only when a file is imported. (Previous versions used to store the cached bytecode as .pyc files that littered up the same directory as the .py files, but starting in Python 3 they were moved to a subdirectory to make things tidier.)
2
u/michalesco May 19 '17
Thanx a lot! Correct me if I am wrong: if I delete the folder, nothing bad happens at it would be created again when the scripts import a module(s) again. Right?
One more question: The folder appeared when I imported my own module, I haven't seen it before. Does it mean that when I import a module from Python standard library, the pycache folder is not created? Is this something like a rule?