Skip to content

Workshop labs

These five labs have working implementations and tests. From the repository root, run uv run --locked python to try the Python snippets interactively. After editing Cython, SWIG, C++, or Rust source, exit Python and run the corresponding pytest command. uv rebuilds the local package when its native sources change.

1. Integrate a cosine with Cython

The left-rectangle rule divides an interval into equal widths, samples the function at each rectangle's left edge, and sums the areas. The integral of cosine from zero to π/2 is exactly one, so you can measure the approximation error directly.

from math import pi
from native_examples.integration import integrate_cos

for steps in (10, 100, 1_000):
    estimate = integrate_cos(0, pi / 2, steps)
    print(steps, round(estimate, 6))
# 10 1.076483
# 100 1.007833
# 1000 1.000785

Read the Cython loop. The index uses Py_ssize_t, the accumulator and width use double, and cos comes from the C math library. The loop releases the GIL while summing each chunk, so other Python threads can run. Between chunks it checks for signals, so Ctrl-C can interrupt a long calculation. Integration source

Try it. Reimplement the same loop in Python with math.cos. Compare both answers for two rectangles on the interval from zero to π, then reverse the bounds. Which endpoint does each approximation sample first?

uv run --locked pytest tests/test_labs.py -k integration

2. Pass a Python buffer to zlib with Cython

The buffer binding accepts any one-dimensional, contiguous buffer of unsigned bytes, including bytes and bytearray. A sliced memoryview can select the region to compress without copying the input.

import zlib
from native_examples import buffer_codec

packet = bytearray(b"HDR" + b"AB" * 500)
payload = memoryview(packet)[3:]
packed = buffer_codec.compress(payload)
assert zlib.decompress(packed) == payload
assert buffer_codec.decompress(packed, len(payload)) == payload

The declaration const unsigned char[::1] gives the wrapper a contiguous input view. The compressor allocates the output using compressBound. For decompression the caller supplies the original size. zlib updates the output length, and the wrapper checks it before returning Python bytes. Buffer binding · zlib utility functions

Try it. Compress 100,000 copies of the same byte, then decompress with the exact size and with an expected size one byte smaller. Which call raises ValueError? Why would allocating a fixed multiple of the compressed size be unreliable?

uv run --locked pytest tests/test_labs.py -k buffer_codec

3. Wrap a C++ byte vector with SWIG

This binding uses the same zlib format. SWIG's std_vector.i converts a Python sequence of integers into a std::vector<unsigned char>. The interface also exposes the vector class as ByteVector so you can build or mutate a C++ container from Python.

import zlib
from native_examples import vector_codec

samples = vector_codec.ByteVector([0, 127, 255])
samples.append(42)
packed = vector_codec.compress(samples)
assert zlib.decompress(packed) == bytes([0, 127, 255, 42])
restored = vector_codec.decompress(list(packed), len(samples))
assert restored == bytes([0, 127, 255, 42])

Read the %template(ByteVector) declaration and the compression signature together. The C++ function borrows its input by const reference and returns its output by value. The output typemap copies the contiguous result directly into a Python bytes object. Iteration uses checked integer indexing, and slices return independent byte vectors. SWIG interface · C++ implementation

Try it. Change the final element in samples, compress it again and decompress with the Cython binding from lab 2. Predict the last byte before inspecting it.

uv run --locked pytest tests/test_labs.py -k "vector_codec or byte_vector"

4. Call a Python logger from C++

A SWIG director routes a C++ virtual method call to an override on a Python subclass. Here, emit_message takes a Logger& and calls its log method synchronously.

from native_examples.callbacks import Logger, emit_message

class Recorder(Logger):
    def __init__(self):
        super().__init__()
        self.messages = []

    def log(self, level, message):
        self.messages.append((level, message))

recorder = Recorder()
emit_message(recorder, 30, "low battery")
assert recorder.messages == [(30, "low battery")]

Python owns the recorder throughout. The C++ function borrows it for one call and keeps no pointer afterward. The SWIG interface enables directors for Logger and returns any exception from the Python override to the original caller. Logger and dispatch function · Director interface · SWIG director exceptions

Try it. Add a Python subclass whose log raises LookupError(message). Call emit_message with it and catch the exception in Python. Trace the path from the call site through the C++ function to the override and back.

uv run --locked pytest tests/test_labs.py -k callback

5. Pass a sequence from Python to Rust with PyO3

Suppose a Python caller needs several Fibonacci terms. Use the workshop’s rust_fibonacci extension to request them in one call. Predict the result for a repeated index and for an empty list, then try both.

from rust_fibonacci import compute_fibonacci, fibonacci_batch

indices = [4, 0, 4, 1]
assert fibonacci_batch(indices) == [8, 1, 8, 2]
assert fibonacci_batch(indices) == [compute_fibonacci(i) for i in indices]
assert fibonacci_batch([]) == []

Find fibonacci_batch in rust/src/lib.rs. PyO3 collects the input sequence into a Rust Vec of handles to Python integers. The function maps the existing compute_fibonacci over those handles. Collecting into PyResult<Vec<u32>> propagates a range error from the scalar function. On success, PyO3 converts the resulting vector into a Python list. Rust implementation

Try it. Rewrite the body of fibonacci_batch using a for loop. Create an empty results vector, call compute_fibonacci for each index, and use Rust’s ? operator to propagate an error before pushing the term. Return Ok(results). Run the tests below, then compare what happens in Python for [0, 45] and [0, 1.5]. Which input reaches the scalar function’s range check, and which fails while PyO3 converts the arguments?

uv run --locked pytest tests/test_labs.py -k rust_fibonacci_batch

The lab tests cover empty inputs, conversion errors, interoperability with Python’s standard library, callback exceptions and object lifetimes. Lab tests