Skip to content

Commit

Permalink
Add documentation for #[pyo3(deprecated)]
Browse files Browse the repository at this point in the history
  • Loading branch information
FlickerSoul committed Jul 19, 2024
1 parent 9428996 commit 49621ba
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions guide/src/function.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,55 @@ The `#[pyo3]` attribute can be used to modify properties of the generated Python
m.add_function(wrap_pyfunction!(pyfunction_with_module, m)?)
}
```
- <a id="deprecated"></a> `#[pyo3(deprecated(message = "...", category = ...))]`

Set this option to mark the function as deprecated. The `message` parameter is a string that will be displayed when the function is called, and the `category` parameter is a string that will be displayed in the deprecation warning. The `category` parameter is optional and has to be a subclass of [`Warning`](https://docs.python.org/3.12/library/exceptions.html#Warning). When the `category` parameter is not provided, the warning will be defaulted to [`DeprecationWarning`](https://docs.python.org/3.12/library/exceptions.html#DeprecationWarning).

**Note**: this attribute does not deprecate the rust function but only raises DeprecationWarning when the function is called from Python. To deprecate the rust function, please add `#[deprecated]` attribute to the function.

The following are examples of using the `#[pyo3(deprecated)]` attribute:

```rust
use std::net::ToSocketAddrs;
use pyo3::prelude::*;

#[pyfunction]
#[pyo3(deprecated(message = "This function is deprecated"))]
fn deprecated_function() -> usize {
42
}

#[pyfunction]
#[pyo3(deprecated(message = "This function is deprecated with FutureWarning", category = PyFutureWarning))]
fn deprecated_function_with_category() -> usize {
42
}

#[pymodule]
fn module_with_deprecated_fn(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(deprecated_function, m)?)?;
m.add_function(wrap_pyfunction!(deprecated_function_with_category, m)?)?;

Ok(())
}
```

When the function is called, a deprecation warning will be displayed:

```python
import warnings
from module_with_deprecated_fn import deprecated_function, deprecated_function_with_category

deprecated_function()
deprecated_function_with_category()
```

The output will be:

```plaintext
DeprecationWarning: This function is deprecated
FutureWarning: This function is deprecated with FutureWarning
```

## Per-argument options

Expand Down

0 comments on commit 49621ba

Please sign in to comment.