You’re the Expert!

pynfinity

Build mountain with each pebble 🧗

Topics | Stepping Stones

📚 Guides

🌍 Pebbles & Contributions

✍️ Write a Post
🐼 Pandas DataFrames
🐼 Pandas DataFrames
🔢 NumPy Arrays
🔢 NumPy Arrays
📉 Matplotlib Plotting
📉 Matplotlib Plotting
🔥 Seaborn Heatmaps
🔥 Seaborn Heatmaps
🤖 Scikit-Learn Linear Regression
🤖 Scikit-Learn Linear Regression
🧹 Data Cleaning with Dropna
🧹 Data Cleaning with Dropna
🔍 Exploratory Data Analysis (EDA)
🔍 Exploratory Data Analysis (EDA)
⏳ Time Series Resampling
⏳ Time Series Resampling
🕸️ Web Scraping with BeautifulSoup
🕸️ Web Scraping with BeautifulSoup
🗄️ SQLAlchemy Basics
🗄️ SQLAlchemy Basics
📊 Interactive Plots with Plotly
📊 Interactive Plots with Plotly
📝 NLTK Tokenization
📝 NLTK Tokenization
🧠 TensorFlow Basics
🧠 TensorFlow Basics
🔥 PyTorch Tensors
🔥 PyTorch Tensors
📉 Statsmodels OLS
📉 Statsmodels OLS
📸 OpenCV Image Reading
📸 OpenCV Image Reading
🕸️ NetworkX Graphs
🕸️ NetworkX Graphs
🗺️ Folium Maps
🗺️ Folium Maps
🚀 Streamlit Apps
🚀 Streamlit Apps
⚡ FastAPI Endpoints
⚡ FastAPI Endpoints
✨ Jupyter Magic Commands
✨ Jupyter Magic Commands
📦 Virtual Environments
📦 Virtual Environments
🌲 Git Basics
🌲 Git Basics
🐳 Dockerfiles
🐳 Dockerfiles
☁️ AWS S3 with Boto3
☁️ AWS S3 with Boto3
🧩 Regular Expressions
🧩 Regular Expressions
λ Lambda Functions
λ Lambda Functions
📜 List Comprehensions
📜 List Comprehensions
⚡ Generators
⚡ Generators
🎀 Decorators
🎀 Decorators
🚪 Context Managers
🚪 Context Managers
🧵 Multithreading
🧵 Multithreading
🎛️ Multiprocessing
🎛️ Multiprocessing
⏳ AsyncIO
⏳ AsyncIO
🏷️ Type Hinting
🏷️ Type Hinting
📦 Dataclasses
📦 Dataclasses
🛡️ Pydantic Models
🛡️ Pydantic Models
🧪 Pytest Testing
🧪 Pytest Testing
🪵 Logging
🪵 Logging
💻 Argparse CLI
💻 Argparse CLI
📄 JSON Handling
📄 JSON Handling
📊 CSV Processing
📊 CSV Processing
🥒 Pickle Serialization
🥒 Pickle Serialization
🖥️ OS Module
🖥️ OS Module
⚙️ Sys Module
⚙️ Sys Module
📚 Collections Module
📚 Collections Module
🔁 Itertools
🔁 Itertools
🛠️ Functools
🛠️ Functools
➗ Math Module
➗ Math Module
+ New Post

🚀 Cython: C-Extensions for Python

Cython is a programming language that is a superset of Python, designed to give C-like performance with Python-like syntax. It allows you to compile Python code into C, which is then compiled into a Python extension module.


🧠 Why Cython?

  • Speed: Can be 100x faster than pure Python for computational tasks.
  • Static Typing: Optional static typing allows C-level optimizations.
  • Interoperability: Easy to call C/C++ libraries.

🛠 Basic Example

Create a file named hello.pyx.

# hello.pyx
def say_hello_to(name):
    print(f"Hello {name}!")

Create a setup.py to build it.

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("hello.pyx")
)

Build it: python setup.py build_ext --inplace

Use it:

import hello
hello.say_hello_to("World")

⚡ Static Typing for Speed

The real power comes when you add types.

Pure Python (Slow):

def fib(n):
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a + b

Cython with Types (Fast):

# fib.pyx
def fib(int n):
    cdef int a = 0
    cdef int b = 1
    while b < n:
        print(b, end=' ')
        a, b = b, a + b
  • cdef: Declares C variables. These are not visible to Python code importing the module.
  • cpdef: Creates a C function that also has a Python wrapper.

🔗 Wrapping C Libraries

Cython makes it easy to interface with external C libraries.

# cmath.pyx
cdef extern from "math.h":
    double sin(double x)

def my_sin(x):
    return sin(x)

📝 Summary

  • Superset of Python: Most Python code is valid Cython code.
  • Compilation: Translates to C, then compiles to machine code.
  • Type Declarations: cdef allows defining C types for massive speedups.
  • Bridge: The best way to write C extensions for Python.

Created with ❤️ by Pynfinity