Appearance
If Python is interpreted, what are .pyc files?
.pyc files are compiled bytecode files that are generated by the Python interpreter when a .py file is imported. They contain the compiled version of the Python code, which reduces import overhead by skipping the compilation step on subsequent runs.
When a .py file is imported, the Python interpreter checks if a corresponding .pyc file exists in the __pycache__ directory (introduced in Python 3.2). If it does, the interpreter uses the .pyc file to execute the code, rather than interpreting the code from the .py file. If the .py file is modified, the .pyc file is automatically regenerated. Note that .pyc files are specific to the platform and Python version they were generated on.
Here is an example of how a .pyc file is generated:
A simple Python module
python
# my_module.py
def my_function():
print("Hello, world!")Make a .pyc file in Python
python
import my_module
# A my_module.pyc file is generated in the __pycache__ directoryYou can also manually compile a module using the py_compile module:
bash
python -m py_compile my_module.pyHere is an example of how a .pyc file is used:
Use a .pyc file in Python
python
# my_module.py
def my_function():
print("Hello, world!")Call a function from a module in Python
python
import my_module
my_module.my_function()
# Hello, world!
# The interpreter uses the my_module.pyc file to execute the code in my_module.my_function()Note: The .pyc files are not human-readable, they are only intended to be used by the Python interpreter.