Skip to main content

watch_callback

Macro watch_callback 

Source
macro_rules! watch_callback {
    ($callback:path) => { ... };
}
Expand description

Creates a context watcher callback from a safe Rust function.

The function must be a path with this signature:

use pyo3::prelude::*;
use pyo3::types::context::{watch_callback, ContextEvent};
use pyo3::types::PyContext;

fn context_changed(
    _py: Python<'_>,
    _event: ContextEvent<'_, '_>,
) -> PyResult<()> {
    Ok(())
}

Python::attach(|py| {
    let _watcher = PyContext::add_watcher(py, watch_callback!(context_changed))?;
    Ok(())
})

A function path is required because CPython’s context watcher callback has no user-data pointer. The macro creates a unique static trampoline for the function, avoiding global callback storage. State can still be shared through safe static synchronization primitives.