From 49621bacdaed5eb8355c705d6cfb793e9bed434e Mon Sep 17 00:00:00 2001 From: Heyuan Zeng Date: Fri, 19 Jul 2024 18:44:04 +0100 Subject: [PATCH] Add documentation for `#[pyo3(deprecated)]` --- guide/src/function.md | 49 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/guide/src/function.md b/guide/src/function.md index 5e6cfaba773..490ec2c68ab 100644 --- a/guide/src/function.md +++ b/guide/src/function.md @@ -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)?) } ``` + - `#[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