Write Python. Run Rust. A Granular Transpilation Framework for Seamless Rust-Python Interoperability.
Project description
Copperhead
Write Python. Run Rust.
Interactive Documentation: copperhead-ad8qypth.manus.space
What is Copperhead?
Copperhead is a programming tool that lets you write code in Python (the easy language) but run it at Rust speeds (the fast language). You get the simplicity of Python with the performance of Rust.
No new language to learn. No complex build steps. Just faster Python.
What's Working Today
- Full compilation pipeline: Python source → AST → Rust code → Cargo build →
.dll/.so - Complete AST coverage: All 28 Python statement types and 27 expression types transpiled to Rust
- 60+ Python builtins mapped to Rust equivalents (len, range, abs, min, max, sum, sorted, etc.)
- 40+ string methods mapped (upper, lower, strip, replace, split, find, join, etc.)
- 10+ Vec/Dict methods mapped (append→push, get, keys, values, items, etc.)
- 16 type primitives mapped to Rust types via PyO3 0.23
- AI code generation from natural language descriptions (verified with Ollama)
- Module registry with 13 pre-loaded examples
- 375 unit tests (all passing) — comprehensive AST coverage, type system, parser, transpiler, compiler, CLI, LLM, registry, debugger
- Package builds and passes PyPI quality checks (
twine check)
Quick Start (2 minutes)
Install
pip install copperhead-rust-puthon
Note: The package name on PyPI is
copperhead-rust-puthon, but you import it ascopperheadand use thecopperheadCLI command.
Write Fast Python
import copperhead as cp
# Mark this function for Rust speed
@cp.compile(target="rust")
def calculate(x: float) -> float:
return x * x + cp.math.sin(x)
# Call it like normal Python
result = calculate(5.0) # Runs at Rust speed!
Run
python my_script.py
Compile to Rust (Optional)
copperhead build my_script.py
This generates a .dll (Windows) or .so (Linux) at native Rust speed.
Why Copperhead?
The Problem
- Python is easy but slow for heavy computations
- Rust is fast but hard to learn and write
- You've been forced to choose between easy and fast
The Solution
Copperhead lets you:
- Write Python (easy)
- Mark functions for Rust speed (simple annotation)
- Get 10-100x faster execution (automatic)
What Makes It Different
| Feature | Copperhead | Other Tools |
|---|---|---|
| Still Python? | Yes, 100% | Usually no |
| Learn new syntax? | No | Yes |
| Gradual optimization? | Yes | No |
| AI code generation? | Yes | No |
| Point to specific functions? | Yes | No |
| Actually compiles to Rust? | Yes | Varies |
Core Features
1. Rich Python Blocks
Mark any function for Rust compilation:
@cp.compile(target="rust")
def my_fast_function(data: list[float]) -> float:
total = 0.0
for x in data:
total += x * x
return total
2. Type System (Optional but Faster)
Add types for even more speed:
@cp.compile(target="rust")
def process(x: cp.f64, y: cp.f64) -> cp.f64:
return x + y
Available types:
cp.i8,cp.i16,cp.i32,cp.i64(integers)cp.f32,cp.f64(decimals)cp.bool(true/false)cp.str(text)list[T],dict[K, V](collections)
3. Ownership (For Advanced Users)
Control how data is passed to Rust:
# Mutable reference (can modify)
def update(state: cp.mut[MyClass]) -> None:
state.value += 1
# Immutable reference (read-only)
def read(data: cp.ref[MyClass]) -> float:
return data.value
4. GIL Release (For Threading)
Enable true parallel processing:
@cp.compile(target="rust")
@cp.no_gil
def cpu_heavy(n: int) -> float:
total = 0.0
for i in range(n):
total += cp.math.sin(float(i))
return total
5. Math Module
Built-in math functions that compile to fast Rust:
cp.math.sin(x) # Sine
cp.math.cos(x) # Cosine
cp.math.sqrt(x) # Square root
cp.math.pow(x, y) # Power
cp.math.log(x) # Natural log
cp.math.min(a, b) # Minimum
cp.math.max(a, b) # Maximum
6. Error Handling
Safe error handling with Rust-style Results:
@cp.compile(target="rust")
def divide(a: float, b: float):
if b == 0.0:
return cp.Err("Cannot divide by zero")
return cp.Ok(a / b)
AI Agent
Copperhead includes an AI assistant that writes code for you.
Generate Code from English
copperhead generate "Create a function that sorts a list using quicksort"
Interactive Mode
copperhead interactive
Then just describe what you want:
You: Create a function that finds prime numbers up to n
AI: [Generates complete Copperhead code with tests]
What the AI Does
- Understands your plain-English description
- Plans the best approach
- Checks if similar code already exists
- Writes complete, tested code
- Debugs it before giving it to you
Interactive Interpreter
A shared workspace for you and the AI:
copperhead interpret
Commands
| Command | What It Does |
|---|---|
<code> |
Add code to workspace |
?<description> |
Ask AI to generate code |
:debug |
Check code for errors |
:test |
Run tests |
:build |
Compile to Rust |
:list |
Show all code blocks |
:save file.py |
Save workspace |
:load file.py |
Load workspace |
:help |
Show all commands |
:exit |
Quit |
Example Session
copperhead> ?Create a function that calculates factorial
[AI generates code with types and tests]
copperhead> :debug
[Checks code for issues]
copperhead> :test
[Runs generated tests]
copperhead> :save factorial.py
[ Saves to file]
Module Registry
Store and reuse your best functions. Ships with 13 pre-loaded examples.
Commands
copperhead registry list # See all modules
copperhead registry search "matrix" # Find specific functions
copperhead registry add script.py # Save a module
copperhead registry stats # See usage statistics
Pre-loaded Examples
Basic (5): sum_list, sort_numbers, factorial, fibonacci, divide
Advanced (8): linear_regression, matrix_multiply, quicksort, binary_search, prime_sieve, word_count, running_average, mandelbrot
Why Use It
- Don't rewrite the same function twice
- Share code with your team
- Track what's working well
Debugging
Check your code before running it.
CLI Debug
copperhead debug script.py # Full debug
copperhead debug script.py --types # Type checking only
What It Checks
- Syntax - Is the code valid Python?
- Types - Are type annotations correct?
- Patterns - Does it follow Copperhead best practices?
- Safety - Is it safe to run?
Building for Production
Compile to fast Rust binaries.
Module Mode (Fast Development)
copperhead build script.py
Compiles just that file. Fast for development.
Bundle Mode (Maximum Performance)
copperhead build --bundle ./project/ -o engine.so
Compiles everything into one optimized binary. Best for production.
Examples
See the demo/ directory:
| File | What It Shows |
|---|---|
standard_python.py |
Standard Python speed baseline |
copperhead_version.py |
Copperhead equivalent |
compare.py |
Side-by-side comparison |
test_ai_generation.py |
AI code generation test |
comprehensive_test.py |
Full integration test suite |
test_ollama_real.py |
Real Ollama AI tests |
test_ambiguous.py |
AI ambiguity handling |
test_interpreter.py |
Interpreter tests |
populate_registry.py |
Registry population script |
Testing
Run All Tests
# 375 tests (196 AST coverage + 179 unit tests)
pytest copperhead/tests/
# Or run the comprehensive test
python comprehensive_test.py
Run Specific Tests
pytest copperhead/tests/test_ast_coverage.py # AST coverage (196 tests)
pytest copperhead/tests/test_types.py # Type system
pytest copperhead/tests/test_parser.py # Parser
pytest copperhead/tests/test_transpiler.py # Transpiler
Architecture
copperhead/
├── copperhead/ # Core package
│ ├── __init__.py # Core types and decorators
│ ├── parser.py # Reads and understands Python code
│ ├── transpiler.py # Converts Python to Rust (28 stmts, 27 exprs, 60+ builtins)
│ ├── compiler.py # Builds Rust binaries via Cargo
│ ├── cli.py # Command-line interface
│ ├── llm.py # AI agent (Ollama)
│ ├── debugger.py # Code validation
│ ├── registry.py # Module database (SQLite)
│ ├── interpreter.py # Interactive workspace
│ ├── examples/ # Package examples
│ └── tests/ # 375 unit tests (196 AST + 179 core)
├── demo/ # Demo and test scripts
├── docs/ # Documentation + GitHub Pages
└── pyproject.toml # Package config
How It Works (Simplified)
Your Python Code
↓
[Parser] - Reads and understands it
↓
[Type Analyzer] - Figures out types
↓
[Rust Generator] - Writes equivalent Rust with PyO3 bindings
↓
[Cargo Compiler] - Creates fast machine code
↓
[Import Hook] - Makes it available to Python
Requirements
- Python 3.8+
- Rust and Cargo (for compilation)
- Ollama (for AI features, optional)
Performance
Typical speedups on real tasks:
| Task | Python | Copperhead | Speedup |
|---|---|---|---|
| Sort 1M numbers | 450ms | 12ms | 37x |
| Image processing | 2.1s | 0.08s | 26x |
| Financial models | 8.5s | 0.3s | 28x |
| JSON parsing | 1.2s | 0.15s | 8x |
FAQ
Q: Do I need to learn Rust? A: No. You write Python. Copperhead handles the Rust.
Q: Will my existing code work?
A: Yes. Add @cp.compile to speed up specific functions.
Q: Is it really that fast? A: Yes. 10-100x faster for CPU-intensive tasks.
Q: Can I use NumPy/Pandas? A: Yes. Copperhead works with existing Python libraries.
Q: How does the AI work? A: It uses Ollama (local AI). Your code never leaves your computer.
Q: What if something breaks? A: Your code still runs as Python, so your debugger works. Copperhead also has its own debugger.
Q: Does the compiler actually work?
A: Yes. The full pipeline has been verified: Python → parse → transpile → Cargo build → .dll/.so.
Learn More
- White Paper - Detailed explanation for everyone
- Technical Deep Dive - How it works internally
- Getting Started - Step-by-step guide
- Tutorial - Learn with examples
- API Reference - Complete function list
- Roadmap - What's coming next
Contributing
Contributions welcome! See the Roadmap for planned features.
# Clone the repo
git clone https://github.com/unaveragetech/copperhead-rust-puthon.git
cd copperhead-rust-puthon
# Install dependencies
pip install -e .
# Run tests
pytest copperhead/tests/
Community
- GitHub Issues: Report bugs or request features
- Discussions: Ask questions
License
SDUC License v1.1 (Small Developer Use Clause) - Free for individuals and small developers. See LICENSE for details.
Copperhead: Write Python. Run Rust.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file copperhead_rust_puthon-0.1.0.tar.gz.
File metadata
- Download URL: copperhead_rust_puthon-0.1.0.tar.gz
- Upload date:
- Size: 122.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d37f03ba221209e2210b86072f781d66eac8c0f86456588ce2ea3c860ec527b6
|
|
| MD5 |
dffa5d3dd449ac71b4c090f4c525f22a
|
|
| BLAKE2b-256 |
5c1ac0dc8e384bd2ca1365b164c1c40e5f6080e1c5a695907bf49ae324b29882
|
File details
Details for the file copperhead_rust_puthon-0.1.0-py3-none-any.whl.
File metadata
- Download URL: copperhead_rust_puthon-0.1.0-py3-none-any.whl
- Upload date:
- Size: 97.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
89aaa3ec3538e72c046e5e68833fb102d649e9e947432b738cffa744f5149164
|
|
| MD5 |
fa61100582431bb3a74178685c88c08a
|
|
| BLAKE2b-256 |
32dea4d692f29f056f1db46098d7d223555dd0a49fb3a8447f5bd781dbd0090c
|