What is exactly __pycache__ in python ?

When you create a python program as simple as HelloWorld, have you ever wondered what happens behind the scene. Or, lets say if you perform a more advanced stuff like importing a local module to call a function declared in another file, how python executes it internally ? Lets deep dive more into this..

We all know python is an interpreted programming language, but its interpreter does not directly operate on the source file instead it compiles the high level source code into a low level byte code which is a intermediary binary representation of the code. This byte code is not a machine code and cannot directly talk to the hardware.

This bytecode is cached in a folder called "__pycache__" which automatically gets created when you import any module. This folder contains .pyc file denoting the specific python implementation like cpython or jython or pypy along with the python version installed. A typical .pyc file will be named like <file-name>.cpython-312.pyc

Everytime you run your python code containing any imports, the interpreter will first look for the compiled bytecode in this cache folder to speed up the execution. If there are any changes to the module, the cache folder gets updated.

Watch this amazing video from Hitesh Choudhary for more details and clear understanding.