pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

Variant constructors for complex *external* enums

Open davidhewitt opened this issue 1 month ago • 0 comments

Discussed in https://github.com/PyO3/pyo3/discussions/5479

Originally posted by ffuugoo September 30, 2025 When using #[pyclass] on a "complex" enum, PyO3 generates a sub-class for each variant, so that you can use isinstance. Is it possible to implement something similar manually, if I'm wrapping an external enum?

I can define #[classmethod]s for each variant, but sub-classes might be nicer, if they are not too terribly difficult to implement.

E.g.:

// External crate
pub enum Something {
	This(This),
	That(That),
}

// My bindings
#[pyclass]
pub struct PySomething(Something);

#[pymethods]
impl PySomething {
	// I can do this, but then I won't be able to use `isinstance` to differentiate variants 🤔
	#[classmethod]
	fn this() -> Self {
		Self(Something::This(This::default()))
	}
}

// How do I annotate/implement `PySomethingThis` so that it's similar to auto-generated `This` sub-class
// when `#[pyclass]` is used on `Something` directly? 
#[pyclass]
pub struct PySomethingThis;
```</div>

----

I think this could potentially use documentation.

davidhewitt avatar Nov 18 '25 13:11 davidhewitt