You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* derive(FromPyObject): adds default option
Takes an optional expression to set a custom value that is not the one from the Default trait
* Documentation, testing and hygiene
* Support enum variant named fields and cover failures
Copy file name to clipboardExpand all lines: guide/src/conversions/traits.md
+42Lines changed: 42 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -488,6 +488,48 @@ If the input is neither a string nor an integer, the error message will be:
488
488
- apply a custom function to convert the field from Python the desired Rust type.
489
489
- the argument must be the name of the function as a string.
490
490
- the function signature must be `fn(&Bound<PyAny>) -> PyResult<T>` where `T` is the Rust type of the argument.
491
+
-`pyo3(default)`, `pyo3(default = ...)`
492
+
- if the argument is set, uses the given default value.
493
+
- in this case, the argument must be a Rust expression returning a value of the desired Rust type.
494
+
- if the argument is not set, [`Default::default`](https://doc.rust-lang.org/std/default/trait.Default.html#tymethod.default) is used.
495
+
- note that the default value is only used if the field is not set.
496
+
If the field is set and the conversion function from Python to Rust fails, an exception is raised and the default value is not used.
497
+
- this attribute is only supported on named fields.
498
+
499
+
For example, the code below applies the given conversion function on the `"value"` dict item to compute its length or fall back to the type default value (0):
`derive(FromPyObject)` allow a `default` attribute to set a default value for extracted fields of named structs. The default value is either provided explicitly or fetched via `Default::default()`.
0 commit comments