Understanding Common Python File Extensions and Their Uses
This article explains the most common Python file extensions—including .py, .ipynb, .pyi, .pyc, .pyd, .pyw, and .pyx—describes their purposes, shows example code for each, and demonstrates how Cython can dramatically improve performance for computation‑intensive tasks.
.py
The most common Python source file extension; it contains plain Python source code.
.ipynb
.ipynb is the file extension for Jupyter Notebook files, also known as IPython Notebooks.
.pyi
.pyi files are type‑hint stub files used by Python for static type checking and analysis.
.pyc
.pyc is the compiled byte‑code file for Python; it stores an intermediate representation of the source code and cannot be read directly because it is binary.
.pyd
.pyd is the extension for compiled Python extension modules written in C or C++. It contains binary code that can be imported in Python just like a regular .py module, providing faster execution for performance‑critical tasks.
.pyw
.pyw is the extension for windowed Python scripts that run without opening a console window, useful for GUI applications.
.pyx
.pyx is the source file extension for Cython, a compiled static‑type extension language that allows Python code to call C for improved performance.
Cython Performance Example
The article includes a Cython implementation of the Fibonacci function and compares its execution time with a pure Python version using timeit . The results show that the Cython version runs roughly twice as fast.
<code>cdef int a, b, i
def fibonacci(n):
if n <= 0:
raise ValueError("n必须是正整数")
if n == 1:
return 0
elif n == 2:
return 1
else:
a = 0
b = 1
for i in range(3, n + 1):
a, b = b, a + b
return b
</code> <code>import fb
import timeit
def fibonacci(n):
if n <= 0:
raise ValueError("n必须是正整数")
if n == 1:
return 0
elif n == 2:
return 1
else:
a, b = 0, 1
for _ in range(3, n + 1):
a, b = b, a + b
return b
# Pure Python version
python_time = timeit.timeit("fibonacci(300)", setup="from __main__ import fibonacci", number=1000000)
# Cython version
cython_time = timeit.timeit("fb.fibonacci(300)", setup="import fb", number=1000000)
print("Pure Python version time:", python_time)
print("Cython version time:", cython_time)
</code>Result:
<code>Pure Python version time: 12.391942400000516
Cython version time: 6.574918199999956
</code>In this compute‑intensive scenario, Cython is nearly twice as fast as pure Python.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.