Chapter 16: Python Libraries
Wyn can compile your code into shared libraries that Python calls directly. C-level performance with Python-level convenience.
Building a Library
Write functions in Wyn:
wyn
// mathlib.wyn
fn add(a: int, b: int) -> int {
return a + b
}
fn factorial(n: int) -> int {
if n <= 1 { return 1 }
return n * factorial(n - 1)
}
fn greet(name: string) -> string {
return "Hello, " + name + "!"
}
fn main() -> int { return 0 }Build with --python:
bash
wyn build mathlib.wyn --pythonThis produces:
libmathlib.dylib(macOS) /.so(Linux) /.dll(Windows)mathlib.py- auto-generated Python wrapper with type hints
Using from Python
python
from mathlib import add, factorial, greet
print(add(2, 3)) # 5
print(factorial(20)) # 2432902008176640000
print(greet("Python")) # Hello, Python!The generated wrapper handles everything:
int→ctypes.c_longlongfloat→ctypes.c_doublestring→ auto encode/decode UTF-8bool→ctypes.c_bool
Type Hints
The generated .py file includes full type hints:
python
def add(a: int, b: int) -> int:
...
def greet(name: str) -> str:
...Your IDE gets autocomplete and type checking for free.
When to Use This
- Performance-critical code - write the hot path in Wyn, call from Python
- Reusable libraries - share compiled code across Python projects
- Gradual migration - move Python code to Wyn one function at a time
Exercises
- Write a Wyn library with
is_prime(n: int) -> booland call it from Python - Build a string processing library with
reverse,word_count, andshout - Benchmark a Wyn fibonacci vs Python fibonacci - measure the speedup
Previous: Chapter 15: Real-World Applications | Next: Chapter 17: Web Development