Hello Pythonistas welcome back. Python is a simple yet interesting language.
Today we will take a deep dive into one of its interesting feature __pycache__ folder.
Before diving into the concept let us take an example.
Contents
Example To Understand When The __pycache__ Folder is Generated.
Create a new folder. Let’s say python_hub.
Inside it create 2 files:
- beginner.py
- intermediate.py
#beginner.py
def beginner_contents():
print("1. Installation")
print("2. Variables and DataTypes")
print("3. Conditionals and Loops")
print("4. Various Data Structures")
print("And So On...")
#intermediate.py
from beginner import beginner_contents
def intermediate_contents():
beginner_contents()
print("\n--------------------------")
print("1. Object Oriented Programming")
print("2. Error Handling")
print("And So On...")
intermediate_contents()
Now run the intermediat.py
file.
You’ll see a new __pycache__ folder.
What is This Folder?
The python code you write can be executed in 2 ways.
- Directly the script is executed in the Python Virtual Machine.
- The ByteCode of the script you wrote is executed.
Now, when you run a code without any import statements, that is when you do not use any package/library (usually programmer-made ones.)
The script is directly executed in Python’s Virtual machine.
And you do not see any such folders.
But in this case, we created 2 files and imported the beginner.py
in our intermediate.py
.
What is The pyc in Python?
Python created and stored the bytecode version of the beginner.py file.
Why?
To improve performance.
Now, bytecode is still not machine code but, it is faster than the Python script you write.
That is why Python creates such pyc files.
These are nothing but the bytecode version of your code.
Do I need to keep Pycache files?
While you are still developing the project I feel it is a good idea to keep them for better performance.
But you can delete them if you wish to.
Is it safe to remove _ pycache _?
It is absolutely safe to remove the __pycache__ folder. You might see a small lag in the execution if the code does a lot of processing.
Otherwise, it should be fine.
Should I commit pycache files?
Committing these files on Github might not be a good idea as the other person using it might not have your version of Python.
Although, it’s not usually problematic. But its better if you do not commit them.