Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 24 additions & 16 deletions guide/src/class.md
Original file line number Diff line number Diff line change
Expand Up @@ -886,7 +886,7 @@ impl MyClass {

## Class attributes

To create a class attribute (also called [class variable][classattr]), a method without any arguments can be annotated with the `#[classattr]` attribute.
To create a class attribute (also called [class variable][classattr]), an associated constant can be annotated with the `#[classattr]` attribute.

```rust,no_run
# use pyo3::prelude::*;
Expand All @@ -895,25 +895,19 @@ To create a class attribute (also called [class variable][classattr]), a method
#[pymethods]
impl MyClass {
#[classattr]
fn my_attribute() -> String {
"hello".to_string()
}
const MY_ATTRIBUTE: &'static str = "foobar";
}

Python::attach(|py| {
let my_class = py.get_type::<MyClass>();
pyo3::py_run!(py, my_class, "assert my_class.my_attribute == 'hello'")
});
#
# Python::attach(|py| {
# let my_class = py.get_type::<MyClass>();
# pyo3::py_run!(py, my_class, "assert my_class.MY_ATTRIBUTE == 'foobar'")
# });
```

> [!NOTE]
> If the method has a `Result` return type and returns an `Err`, PyO3 will panic during
class creation.
If `const` code is too limiting, a method without any arguments can be annotated with the `#[classattr]` attribute.

> [!NOTE]
> `#[classattr]` does not work with [`#[pyo3(warn(...))]`](./function.md#warn) attribute.

If the class attribute is defined with `const` code only, one can also annotate associated constants:
> Here too, the class attribute value is computed once during the class creation and not each time the attribute is accessed.

```rust,no_run
# use pyo3::prelude::*;
Expand All @@ -922,10 +916,24 @@ If the class attribute is defined with `const` code only, one can also annotate
#[pymethods]
impl MyClass {
#[classattr]
const MY_CONST_ATTRIBUTE: &'static str = "foobar";
fn my_attribute() -> String {
"hello".to_string()
}
}
#
# Python::attach(|py| {
# let my_class = py.get_type::<MyClass>();
# pyo3::py_run!(py, my_class, "assert my_class.my_attribute == 'hello'")
# });
```

> [!NOTE]
> If the method has a `Result` return type and returns an `Err`, PyO3 will panic during
class creation.

> [!NOTE]
> `#[classattr]` does not work with [`#[pyo3(warn(...))]`](./function.md#warn) attribute.

## Classes as function arguments

Class objects can be used as arguments to `#[pyfunction]`s and `#[pymethods]` in the same way as the self parameters of instance methods, i.e. they can be passed as:
Expand Down
Loading