Skip to content

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 --python

This 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:

  • intctypes.c_longlong
  • floatctypes.c_double
  • string → auto encode/decode UTF-8
  • boolctypes.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

  1. Write a Wyn library with is_prime(n: int) -> bool and call it from Python
  2. Build a string processing library with reverse, word_count, and shout
  3. Benchmark a Wyn fibonacci vs Python fibonacci - measure the speedup

Previous: Chapter 15: Real-World Applications | Next: Chapter 17: Web Development

MIT License - v1.19.1