-
Defining a complex enum e.g: #[pyclass(eq)]
#[derive(Debug, Clone, PartialEq)]
pub enum MyEnum {
A { val: u32 },
B { name: String },
} can be typed in the stub file as: class MyEnum:
@classmethod
def A(cls, val: int) -> MyEnum: ...
@classmethod
def B(cls, name: str) -> MyEnum: ... Although when using Python isinstance(obj, MyEnum.A): # test works but mypy complains incompatible type.
obj.val # <-- mypy error since val is not a declared attribute Complex Enums are very useful objects in PyO3 but I struggle with these properties and pickling them which is another issue. Anyone with any ideas? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Complex enums are build using a class hierarchy. Each variant will be it's own class inheriting from a common base class for all variants. The base class has attributes for each variant class. Something like the following: class MyEnum:
A: MyEnumA
B: MyEnumB
class MyEnumA(MyEnum):
val: int
class MyEnumB(MyEnum):
name: str I think this can also be written like this, which reads a little nicer. class MyEnum:
class A(MyEnum):
val: int
class B(MyEnum):
name: str |
Beta Was this translation helpful? Give feedback.
Thanks I needed to extend this to:
But this did indeed solve many
mypy
errors.