Skip to content

Commit d9b2abd

Browse files
committed
removes implicit default of trailing optional arguments (see #2935)
1 parent 7bd8df8 commit d9b2abd

16 files changed

+49
-265
lines changed

guide/src/function/signature.md

Lines changed: 1 addition & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
The `#[pyfunction]` attribute also accepts parameters to control how the generated Python function accepts arguments. Just like in Python, arguments can be positional-only, keyword-only, or accept either. `*args` lists and `**kwargs` dicts can also be accepted. These parameters also work for `#[pymethods]` which will be introduced in the [Python Classes](../class.md) section of the guide.
44

5-
Like Python, by default PyO3 accepts all arguments as either positional or keyword arguments. Most arguments are required by default, except for trailing `Option<_>` arguments, which are [implicitly given a default of `None`](#trailing-optional-arguments). This behaviour can be configured by the `#[pyo3(signature = (...))]` option which allows writing a signature in Python syntax.
5+
Like Python, by default PyO3 accepts all arguments as either positional or keyword arguments. All arguments are required by default. This behaviour can be configured by the `#[pyo3(signature = (...))]` option which allows writing a signature in Python syntax.
66

77
This section of the guide goes into detail about use of the `#[pyo3(signature = (...))]` option and its related option `#[pyo3(text_signature = "...")]`
88

@@ -118,82 +118,6 @@ num=-1
118118
> }
119119
> ```
120120
121-
## Trailing optional arguments
122-
123-
<div class="warning">
124-
125-
⚠️ Warning: This behaviour is being phased out 🛠️
126-
127-
The special casing of trailing optional arguments is deprecated. In a future `pyo3` version, arguments of type `Option<..>` will share the same behaviour as other arguments, they are required unless a default is set using `#[pyo3(signature = (...))]`.
128-
129-
This is done to better align the Python and Rust definition of such functions and make it more intuitive to rewrite them from Python in Rust. Specifically `def some_fn(a: int, b: Optional[int]): ...` will not automatically default `b` to `none`, but requires an explicit default if desired, where as in current `pyo3` it is handled the other way around.
130-
131-
During the migration window a `#[pyo3(signature = (...))]` will be required to silence the deprecation warning. After support for trailing optional arguments is fully removed, the signature attribute can be removed if all arguments should be required.
132-
</div>
133-
134-
135-
As a convenience, functions without a `#[pyo3(signature = (...))]` option will treat trailing `Option<T>` arguments as having a default of `None`. In the example below, PyO3 will create `increment` with a signature of `increment(x, amount=None)`.
136-
137-
```rust
138-
#![allow(deprecated)]
139-
use pyo3::prelude::*;
140-
141-
/// Returns a copy of `x` increased by `amount`.
142-
///
143-
/// If `amount` is unspecified or `None`, equivalent to `x + 1`.
144-
#[pyfunction]
145-
fn increment(x: u64, amount: Option<u64>) -> u64 {
146-
x + amount.unwrap_or(1)
147-
}
148-
#
149-
# fn main() -> PyResult<()> {
150-
# Python::with_gil(|py| {
151-
# let fun = pyo3::wrap_pyfunction!(increment, py)?;
152-
#
153-
# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?;
154-
# let sig: String = inspect
155-
# .call1((fun,))?
156-
# .call_method0("__str__")?
157-
# .extract()?;
158-
#
159-
# #[cfg(Py_3_8)] // on 3.7 the signature doesn't render b, upstream bug?
160-
# assert_eq!(sig, "(x, amount=None)");
161-
#
162-
# Ok(())
163-
# })
164-
# }
165-
```
166-
167-
To make trailing `Option<T>` arguments required, but still accept `None`, add a `#[pyo3(signature = (...))]` annotation. For the example above, this would be `#[pyo3(signature = (x, amount))]`:
168-
169-
```rust
170-
# use pyo3::prelude::*;
171-
#[pyfunction]
172-
#[pyo3(signature = (x, amount))]
173-
fn increment(x: u64, amount: Option<u64>) -> u64 {
174-
x + amount.unwrap_or(1)
175-
}
176-
#
177-
# fn main() -> PyResult<()> {
178-
# Python::with_gil(|py| {
179-
# let fun = pyo3::wrap_pyfunction!(increment, py)?;
180-
#
181-
# let inspect = PyModule::import(py, "inspect")?.getattr("signature")?;
182-
# let sig: String = inspect
183-
# .call1((fun,))?
184-
# .call_method0("__str__")?
185-
# .extract()?;
186-
#
187-
# #[cfg(Py_3_8)] // on 3.7 the signature doesn't render b, upstream bug?
188-
# assert_eq!(sig, "(x, amount)");
189-
#
190-
# Ok(())
191-
# })
192-
# }
193-
```
194-
195-
To help avoid confusion, PyO3 requires `#[pyo3(signature = (...))]` when an `Option<T>` argument is surrounded by arguments which aren't `Option<T>`.
196-
197121
## Making the function signature available to Python
198122
199123
The function signature is exposed to Python via the `__text_signature__` attribute. PyO3 automatically generates this for every `#[pyfunction]` and all `#[pymethods]` directly from the Rust function, taking into account any override done with the `#[pyo3(signature = (...))]` option.

guide/src/migration.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -872,7 +872,7 @@ Python::with_gil(|py| -> PyResult<()> {
872872
<details>
873873
<summary><small>Click to expand</small></summary>
874874

875-
[Trailing `Option<T>` arguments](./function/signature.md#trailing-optional-arguments) have an automatic default of `None`. To avoid unwanted changes when modifying function signatures, in PyO3 0.18 it was deprecated to have a required argument after an `Option<T>` argument without using `#[pyo3(signature = (...))]` to specify the intended defaults. In PyO3 0.20, this becomes a hard error.
875+
Trailing `Option<T>` arguments have an automatic default of `None`. To avoid unwanted changes when modifying function signatures, in PyO3 0.18 it was deprecated to have a required argument after an `Option<T>` argument without using `#[pyo3(signature = (...))]` to specify the intended defaults. In PyO3 0.20, this becomes a hard error.
876876

877877
Before:
878878

@@ -1095,7 +1095,7 @@ Starting with PyO3 0.18, this is deprecated and a future PyO3 version will requi
10951095

10961096
Before, x in the below example would be required to be passed from Python code:
10971097

1098-
```rust,compile_fail
1098+
```rust,compile_fail,ignore
10991099
# #![allow(dead_code)]
11001100
# use pyo3::prelude::*;
11011101

newsfragments/4729.removed.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
removes implicit default of trailing optional arguments (see #2935)

pyo3-macros-backend/src/deprecations.rs

Lines changed: 0 additions & 54 deletions
This file was deleted.

pyo3-macros-backend/src/lib.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
mod utils;
1010

1111
mod attributes;
12-
mod deprecations;
1312
mod frompyobject;
1413
mod intopyobject;
1514
mod konst;

pyo3-macros-backend/src/method.rs

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ use proc_macro2::{Span, TokenStream};
66
use quote::{format_ident, quote, quote_spanned, ToTokens};
77
use syn::{ext::IdentExt, spanned::Spanned, Ident, Result};
88

9-
use crate::deprecations::deprecate_trailing_option_default;
109
use crate::pyversions::is_abi3_before;
1110
use crate::utils::{Ctx, LitCStr};
1211
use crate::{
@@ -474,7 +473,7 @@ impl<'a> FnSpec<'a> {
474473
let signature = if let Some(signature) = signature {
475474
FunctionSignature::from_arguments_and_attribute(arguments, signature)?
476475
} else {
477-
FunctionSignature::from_arguments(arguments)?
476+
FunctionSignature::from_arguments(arguments)
478477
};
479478

480479
let convention = if matches!(fn_type, FnType::FnNew | FnType::FnNewClass(_)) {
@@ -745,8 +744,6 @@ impl<'a> FnSpec<'a> {
745744
quote!(#func_name)
746745
};
747746

748-
let deprecation = deprecate_trailing_option_default(self);
749-
750747
Ok(match self.convention {
751748
CallingConvention::Noargs => {
752749
let mut holders = Holders::new();
@@ -767,7 +764,6 @@ impl<'a> FnSpec<'a> {
767764
py: #pyo3_path::Python<'py>,
768765
_slf: *mut #pyo3_path::ffi::PyObject,
769766
) -> #pyo3_path::PyResult<*mut #pyo3_path::ffi::PyObject> {
770-
#deprecation
771767
let function = #rust_name; // Shadow the function name to avoid #3017
772768
#init_holders
773769
let result = #call;
@@ -789,7 +785,6 @@ impl<'a> FnSpec<'a> {
789785
_nargs: #pyo3_path::ffi::Py_ssize_t,
790786
_kwnames: *mut #pyo3_path::ffi::PyObject
791787
) -> #pyo3_path::PyResult<*mut #pyo3_path::ffi::PyObject> {
792-
#deprecation
793788
let function = #rust_name; // Shadow the function name to avoid #3017
794789
#arg_convert
795790
#init_holders
@@ -811,7 +806,6 @@ impl<'a> FnSpec<'a> {
811806
_args: *mut #pyo3_path::ffi::PyObject,
812807
_kwargs: *mut #pyo3_path::ffi::PyObject
813808
) -> #pyo3_path::PyResult<*mut #pyo3_path::ffi::PyObject> {
814-
#deprecation
815809
let function = #rust_name; // Shadow the function name to avoid #3017
816810
#arg_convert
817811
#init_holders
@@ -836,7 +830,6 @@ impl<'a> FnSpec<'a> {
836830
_kwargs: *mut #pyo3_path::ffi::PyObject
837831
) -> #pyo3_path::PyResult<*mut #pyo3_path::ffi::PyObject> {
838832
use #pyo3_path::impl_::callback::IntoPyCallbackOutput;
839-
#deprecation
840833
let function = #rust_name; // Shadow the function name to avoid #3017
841834
#arg_convert
842835
#init_holders

pyo3-macros-backend/src/params.rs

Lines changed: 25 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -245,10 +245,7 @@ pub(crate) fn impl_regular_arg_param(
245245
// Option<T> arguments have special treatment: the default should be specified _without_ the
246246
// Some() wrapper. Maybe this should be changed in future?!
247247
if arg.option_wrapped_type.is_some() {
248-
default = Some(default.map_or_else(
249-
|| quote!(::std::option::Option::None),
250-
|tokens| some_wrap(tokens, ctx),
251-
));
248+
default = default.map(|tokens| some_wrap(tokens, ctx));
252249
}
253250

254251
if arg.from_py_with.is_some() {
@@ -273,31 +270,32 @@ pub(crate) fn impl_regular_arg_param(
273270
)?
274271
}
275272
}
276-
} else if arg.option_wrapped_type.is_some() {
277-
let holder = holders.push_holder(arg.name.span());
278-
quote_arg_span! {
279-
#pyo3_path::impl_::extract_argument::extract_optional_argument(
280-
#arg_value,
281-
&mut #holder,
282-
#name_str,
283-
#[allow(clippy::redundant_closure)]
284-
{
285-
|| #default
286-
}
287-
)?
288-
}
289273
} else if let Some(default) = default {
290274
let holder = holders.push_holder(arg.name.span());
291-
quote_arg_span! {
292-
#pyo3_path::impl_::extract_argument::extract_argument_with_default(
293-
#arg_value,
294-
&mut #holder,
295-
#name_str,
296-
#[allow(clippy::redundant_closure)]
297-
{
298-
|| #default
299-
}
300-
)?
275+
if arg.option_wrapped_type.is_some() {
276+
quote_arg_span! {
277+
#pyo3_path::impl_::extract_argument::extract_optional_argument(
278+
#arg_value,
279+
&mut #holder,
280+
#name_str,
281+
#[allow(clippy::redundant_closure)]
282+
{
283+
|| #default
284+
}
285+
)?
286+
}
287+
} else {
288+
quote_arg_span! {
289+
#pyo3_path::impl_::extract_argument::extract_argument_with_default(
290+
#arg_value,
291+
&mut #holder,
292+
#name_str,
293+
#[allow(clippy::redundant_closure)]
294+
{
295+
|| #default
296+
}
297+
)?
298+
}
301299
}
302300
} else {
303301
let holder = holders.push_holder(arg.name.span());

pyo3-macros-backend/src/pyclass.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1660,7 +1660,7 @@ fn complex_enum_struct_variant_new<'a>(
16601660
constructor.into_signature(),
16611661
)?
16621662
} else {
1663-
crate::pyfunction::FunctionSignature::from_arguments(args)?
1663+
crate::pyfunction::FunctionSignature::from_arguments(args)
16641664
};
16651665

16661666
let spec = FnSpec {
@@ -1714,7 +1714,7 @@ fn complex_enum_tuple_variant_new<'a>(
17141714
constructor.into_signature(),
17151715
)?
17161716
} else {
1717-
crate::pyfunction::FunctionSignature::from_arguments(args)?
1717+
crate::pyfunction::FunctionSignature::from_arguments(args)
17181718
};
17191719

17201720
let spec = FnSpec {
@@ -1737,7 +1737,7 @@ fn complex_enum_variant_field_getter<'a>(
17371737
field_span: Span,
17381738
ctx: &Ctx,
17391739
) -> Result<MethodAndMethodDef> {
1740-
let signature = crate::pyfunction::FunctionSignature::from_arguments(vec![])?;
1740+
let signature = crate::pyfunction::FunctionSignature::from_arguments(vec![]);
17411741

17421742
let self_type = crate::method::SelfType::TryFromBoundRef(field_span);
17431743

pyo3-macros-backend/src/pyfunction.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ pub fn impl_wrap_pyfunction(
239239
let signature = if let Some(signature) = signature {
240240
FunctionSignature::from_arguments_and_attribute(arguments, signature)?
241241
} else {
242-
FunctionSignature::from_arguments(arguments)?
242+
FunctionSignature::from_arguments(arguments)
243243
};
244244

245245
let spec = method::FnSpec {

pyo3-macros-backend/src/pyfunction/signature.rs

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -459,25 +459,19 @@ impl<'a> FunctionSignature<'a> {
459459
}
460460

461461
/// Without `#[pyo3(signature)]` or `#[args]` - just take the Rust function arguments as positional.
462-
pub fn from_arguments(arguments: Vec<FnArg<'a>>) -> syn::Result<Self> {
462+
pub fn from_arguments(arguments: Vec<FnArg<'a>>) -> Self {
463463
let mut python_signature = PythonSignature::default();
464464
for arg in &arguments {
465465
// Python<'_> arguments don't show in Python signature
466466
if matches!(arg, FnArg::Py(..) | FnArg::CancelHandle(..)) {
467467
continue;
468468
}
469469

470-
if let FnArg::Regular(RegularArg {
471-
ty,
472-
option_wrapped_type: None,
473-
..
474-
}) = arg
475-
{
470+
if let FnArg::Regular(RegularArg { .. }) = arg {
476471
// This argument is required, all previous arguments must also have been required
477-
ensure_spanned!(
478-
python_signature.required_positional_parameters == python_signature.positional_parameters.len(),
479-
ty.span() => "required arguments after an `Option<_>` argument are ambiguous\n\
480-
= help: add a `#[pyo3(signature)]` annotation on this function to unambiguously specify the default values for all optional parameters"
472+
assert_eq!(
473+
python_signature.required_positional_parameters,
474+
python_signature.positional_parameters.len(),
481475
);
482476

483477
python_signature.required_positional_parameters =
@@ -489,11 +483,11 @@ impl<'a> FunctionSignature<'a> {
489483
.push(arg.name().unraw().to_string());
490484
}
491485

492-
Ok(Self {
486+
Self {
493487
arguments,
494488
python_signature,
495489
attribute: None,
496-
})
490+
}
497491
}
498492

499493
fn default_value_for_parameter(&self, parameter: &str) -> String {

0 commit comments

Comments
 (0)