1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//! When you want to expose an **state machine** enum to Python,
//! you should implement the trait in this module.
//!
//! # Tips
//!
//! In most cases, `enum` is just like Python's `Union` type, rather than a state machine.
//! For such cases, you can directly return the matched `FooEnum`,
//! without creating a newtype `struct Foo(third_party::Foo)`.
//!
//! # Example:
/*!
```rust
use pyo3::prelude::*;
use pyo3_utils::py_match::PyMatchRef;
mod third_party {
pub enum Foo {
A { a: i32 },
}
}
#[pyclass(frozen)]
#[non_exhaustive]
enum FooEnum {
A { a: i32 },
}
#[pyclass(frozen)]
#[non_exhaustive]
struct Foo(third_party::Foo);
impl PyMatchRef for Foo {
type Output = FooEnum;
fn match_ref(&self) -> Self::Output {
match &self.0 {
third_party::Foo::A { a } => FooEnum::A { a: *a },
}
}
}
// In the future, we might provide a macro to automatically generate this pymethod,
// for now, please do it manually.
#[pymethods]
impl Foo {
fn match_ref(&self) -> <Self as PyMatchRef>::Output {
<Self as PyMatchRef>::match_ref(self)
}
}
```
*/
/// It is recommended to implement this trait only when using `clone` in [PyMatchRef]/[PyMatchMut]
/// would significantly impact memory/performance.