Skip to main content

add_enum

Function add_enum 

Source
pub fn add_enum<T: PyEnum>(module: &Bound<'_, PyModule>) -> PyResult<()>
Expand description

Register the Python class for T onto module under T::SPEC.name.

Triggers a one-time class construction on the first call per interpreter per enum type (subsequent calls reuse the cached class). Prefer the extension-method form PyModuleExt::add_enum inside #[pymodule] bodies; this free function exists for call sites that want an explicit type parameter.

If module already has an attribute with the same name, it is silently replaced — consistent with PyModule::add and m.add_class::<T>()?. Avoid registering two enums whose #[pyenum(name = "...")] resolves to the same string within a single module.

use pyenum::{PyEnum, add_enum};
use pyo3::prelude::*;

#[derive(Clone, Copy, PyEnum)]
pub enum Color { Red, Green, Blue }

#[pymodule]
fn demo(m: &Bound<'_, PyModule>) -> PyResult<()> {
    add_enum::<Color>(m)
}