Skip to content

Commit 73d1a99

Browse files
committed
Update guide
1 parent 91a73bc commit 73d1a99

File tree

2 files changed

+127
-11
lines changed

2 files changed

+127
-11
lines changed

guide/src/class.md

+125-9
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
PyO3 exposes a group of attributes powered by Rust's proc macro system for defining Python classes as Rust structs.
44

5-
The main attribute is `#[pyclass]`, which is placed upon a Rust `struct` to generate a Python type for it. A struct will usually also have *one* `#[pymethods]`-annotated `impl` block for the struct, which is used to define Python methods and constants for the generated Python type. (If the [`multiple-pymethods`] feature is enabled each `#[pyclass]` is allowed to have multiple `#[pymethods]` blocks.) Finally, there may be multiple `#[pyproto]` trait implementations for the struct, which are used to define certain python magic methods such as `__str__`.
5+
The main attribute is `#[pyclass]`, which is placed upon a Rust `struct` or a fieldless `enum` (a.k.a. C-like enum) to generate a Python type for it. They will usually also have *one* `#[pymethods]`-annotated `impl` block for the struct, which is used to define Python methods and constants for the generated Python type. (If the [`multiple-pymethods`] feature is enabled each `#[pyclass]` is allowed to have multiple `#[pymethods]` blocks.) Finally, there may be multiple `#[pyproto]` trait implementations for the struct, which are used to define certain python magic methods such as `__str__`.
66

77
This chapter will discuss the functionality and configuration these attributes offer. Below is a list of links to the relevant section of this chapter for each:
88

@@ -20,9 +20,7 @@ This chapter will discuss the functionality and configuration these attributes o
2020

2121
## Defining a new class
2222

23-
To define a custom Python class, a Rust struct needs to be annotated with the
24-
`#[pyclass]` attribute.
25-
23+
To define a custom Python class, add `#[pyclass]` attribute to a Rust struct or a fieldless enum.
2624
```rust
2725
# #![allow(dead_code)]
2826
# use pyo3::prelude::*;
@@ -31,11 +29,17 @@ struct MyClass {
3129
# #[pyo3(get)]
3230
num: i32,
3331
}
32+
33+
#[pyclass]
34+
enum MyEnum {
35+
Variant,
36+
OtherVariant = 30, // support custom discriminant.
37+
}
3438
```
3539

36-
Because Python objects are freely shared between threads by the Python interpreter, all structs annotated with `#[pyclass]` must implement `Send` (unless annotated with [`#[pyclass(unsendable)]`](#customizing-the-class)).
40+
Because Python objects are freely shared between threads by the Python interpreter, all types annotated with `#[pyclass]` must implement `Send` (unless annotated with [`#[pyclass(unsendable)]`](#customizing-the-class)).
3741

38-
The above example generates implementations for [`PyTypeInfo`], [`PyTypeObject`], and [`PyClass`] for `MyClass`. To see these generated implementations, refer to the [implementation details](#implementation-details) at the end of this chapter.
42+
The above example generates implementations for [`PyTypeInfo`], [`PyTypeObject`], and [`PyClass`] for `MyClass` and `MyEnum`. To see these generated implementations, refer to the [implementation details](#implementation-details) at the end of this chapter.
3943

4044
## Adding the class to a module
4145

@@ -140,8 +144,8 @@ so that they can benefit from a freelist. `XXX` is a number of items for the fre
140144
* `gc` - Classes with the `gc` parameter participate in Python garbage collection.
141145
If a custom class contains references to other Python objects that can be collected, the [`PyGCProtocol`]({{#PYO3_DOCS_URL}}/pyo3/class/gc/trait.PyGCProtocol.html) trait has to be implemented.
142146
* `weakref` - Adds support for Python weak references.
143-
* `extends=BaseType` - Use a custom base class. The base `BaseType` must implement `PyTypeInfo`.
144-
* `subclass` - Allows Python classes to inherit from this class.
147+
* `extends=BaseType` - Use a custom base class. The base `BaseType` must implement `PyTypeInfo`. Enums can't have custom base class.
148+
* `subclass` - Allows Python classes to inherit from this class. Enums cannot be inherited.
145149
* `dict` - Adds `__dict__` support, so that the instances of this type have a dictionary containing arbitrary instance variables.
146150
* `unsendable` - Making it safe to expose `!Send` structs to Python, where all object can be accessed
147151
by multiple threads. A class marked with `unsendable` panics when accessed by another thread.
@@ -350,7 +354,7 @@ impl SubClass {
350354

351355
## Object properties
352356

353-
PyO3 supports two ways to add properties to your `#[pyclass]`:
357+
PyO3 supports two ways to add properties to your `#[pyclass]` struct:
354358
- For simple fields with no side effects, a `#[pyo3(get, set)]` attribute can be added directly to the field definition in the `#[pyclass]`.
355359
- For properties which require computation you can define `#[getter]` and `#[setter]` functions in the [`#[pymethods]`](#instance-methods) block.
356360

@@ -802,6 +806,118 @@ impl MyClass {
802806
Note that `text_signature` on classes is not compatible with compilation in
803807
`abi3` mode until Python 3.10 or greater.
804808

809+
## #[pyclass] enums
810+
811+
Currently PyO3 only supports fieldless enums. PyO3 adds a class attribute for each variant, so you can access them in Python without defining `#[new]`. PyO3 also provides default implementations of `__richcmp__` and `__int__`, so they can be compared using `==`:
812+
813+
```rust
814+
# use pyo3::prelude::*;
815+
#[pyclass]
816+
enum MyEnum {
817+
Variant,
818+
OtherVariant,
819+
}
820+
821+
Python::with_gil(|py| {
822+
let x = Py::new(py, MyEnum::Variant).unwrap();
823+
let y = Py::new(py, MyEnum::OtherVariant).unwrap();
824+
let cls = py.get_type::<MyEnum>();
825+
pyo3::py_run!(py, x y cls, r#"
826+
assert x == cls.Variant
827+
assert y == cls.OtherVariant
828+
assert x != y
829+
"#)
830+
})
831+
```
832+
833+
You can also convert your enums into `int`:
834+
835+
```rust
836+
# use pyo3::prelude::*;
837+
#[pyclass]
838+
enum MyEnum {
839+
Variant,
840+
OtherVariant = 10,
841+
}
842+
843+
Python::with_gil(|py| {
844+
let cls = py.get_type::<MyEnum>();
845+
let x = MyEnum::Variant as i32; // The exact value is assigned by the compiler.
846+
pyo3::py_run!(py, cls x, r#"
847+
assert int(cls.Variant) == x
848+
assert int(cls.OtherVariant) == 10
849+
assert cls.OtherVariant == 10 # You can also compare against int.
850+
assert 10 == cls.OtherVariant
851+
"#)
852+
})
853+
```
854+
855+
PyO3 also provides `__repr__` for enums:
856+
857+
```rust
858+
# use pyo3::prelude::*;
859+
#[pyclass]
860+
enum MyEnum{
861+
Variant,
862+
OtherVariant,
863+
}
864+
865+
Python::with_gil(|py| {
866+
let cls = py.get_type::<MyEnum>();
867+
let x = Py::new(py, MyEnum::Variant).unwrap();
868+
pyo3::py_run!(py, cls x, r#"
869+
assert repr(x) == 'MyEnum.Variant'
870+
assert repr(cls.OtherVariant) == 'MyEnum.OtherVariant'
871+
"#)
872+
})
873+
```
874+
875+
All methods defined by PyO3 can be overriden. For example here's how you override `__repr__`:
876+
877+
```rust
878+
# use pyo3::prelude::*;
879+
#[pyclass]
880+
enum MyEnum {
881+
Answer = 42,
882+
}
883+
884+
#[pymethods]
885+
impl MyEnum {
886+
fn __repr__(&self) -> &'static str {
887+
"42"
888+
}
889+
}
890+
891+
Python::with_gil(|py| {
892+
let cls = py.get_type::<MyEnum>();
893+
pyo3::py_run!(py, cls, "assert repr(cls.Answer) == '42'")
894+
})
895+
```
896+
897+
You may not use enums as a base class or let enums inherit from other classes.
898+
899+
```rust,compile_fail
900+
# use pyo3::prelude::*;
901+
#[pyclass(subclass)]
902+
enum BadBase{
903+
Var1,
904+
}
905+
```
906+
907+
```rust,compile_fail
908+
# use pyo3::prelude::*;
909+
910+
#[pyclass(subclass)]
911+
struct Base;
912+
913+
#[pyclass(extends=Base)]
914+
enum BadSubclass{
915+
Var1,
916+
}
917+
```
918+
919+
It's currently not iteroperable with `IntEnum` in Python.
920+
805921
## Implementation details
806922

807923
The `#[pyclass]` macros rely on a lot of conditional code generation: each `#[pyclass]` can optionally have a `#[pymethods]` block as well as several different possible `#[pyproto]` trait implementations.

pyo3-macros/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ pub fn pyproto(_: TokenStream, input: TokenStream) -> TokenStream {
7777
.into()
7878
}
7979

80-
/// A proc macro used to expose Rust structs as Python objects.
80+
/// A proc macro used to expose Rust structs and fieldless enums as Python objects.
8181
///
8282
/// `#[pyclass]` accepts the following [parameters][2]:
8383
///
@@ -88,7 +88,7 @@ pub fn pyproto(_: TokenStream, input: TokenStream) -> TokenStream {
8888
/// | `gc` | Participate in Python's [garbage collection][5]. Required if your type contains references to other Python objects. If you don't (or incorrectly) implement this, contained Python objects may be hidden from Python's garbage collector and you may leak memory. Note that leaking memory, while undesirable, [is safe behavior][7].|
8989
/// | `weakref` | Allows this class to be [weakly referenceable][6]. |
9090
/// | <span style="white-space: pre">`extends = BaseType`</span> | Use a custom baseclass. Defaults to [`PyAny`][4] |
91-
/// | `subclass` | Allows other Python classes and `#[pyclass]` to inherit from this class. |
91+
/// | `subclass` | Allows other Python classes and `#[pyclass]` to inherit from this class. Enums cannot be subclassEnums cannot be subclassed. |
9292
/// | `unsendable` | Required if your struct is not [`Send`][3]. Rather than using `unsendable`, consider implementing your struct in a threadsafe way by e.g. substituting [`Rc`][8] with [`Arc`][9]. By using `unsendable`, your class will panic when accessed by another thread.|
9393
/// | <span style="white-space: pre">`module = "module_name"`</span> | Python code will see the class as being defined in this module. Defaults to `builtins`. |
9494
///

0 commit comments

Comments
 (0)