PyO3 / PyO3/pyo3

Variant constructors for complex *external* enums

Open
#5,635 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

documentation
Dominant language
Rust
Stars
16.2k
Forks
1k
Avg merge
2d 6h
Merged PRs (30d)
66

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Read Discussion #5479 and the shown #[pyclass]/#[pymethods] example first; determine whether external enums can expose variant-specific Python subclasses with isinstance. Done means documenting a supported pattern or clearly stating the limitation and any required API or design changes.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
api
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.