What is the use of __pycache__?
The __pycache__
directory is automatically created by Python to store compiled bytecode files (.pyc
files) when you import modules. Here's what you need to know:
- Purpose:
- Speeds up subsequent imports of the same module
- Contains pre-compiled bytecode (optimized intermediate format) instead of re-parsing source code every time
- Characteristics:
- Files are named like
module.cpython-310.pyc
(includes Python version) - Automatically regenerated when source files change
- Typically excluded from version control (add to
.gitignore
)
- When it's created:
my_project/
├── __pycache__/ # Auto-generated
│ └── module.cpython-310.pyc
└── module.py # Your source file
- Best practices:
- Don't commit these files to Git
- Safe to delete (Python will regenerate them)
- Helps performance in multi-import scenarios
You can disable bytecode caching by running Python with the -B
flag: