Skip to content

Commit

Permalink
guide: doctest function/ subpages
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Sep 29, 2022
1 parent 2708270 commit a549c55
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
25 changes: 21 additions & 4 deletions guide/src/function/error_handling.md
Expand Up @@ -46,7 +46,7 @@ fn check_positive(x: i32) -> PyResult<()> {
# Python::with_gil(|py|{
# let fun = pyo3::wrap_pyfunction!(check_positive, py).unwrap();
# fun.call1((-1,)).unwrap_err();
# fun.call1((1)).unwrap();
# fun.call1((1,)).unwrap();
# });
# }
```
Expand All @@ -69,6 +69,14 @@ use std::num::ParseIntError;
fn parse_int(x: &str) -> Result<usize, ParseIntError> {
x.parse()
}

# fn main() {
# Python::with_gil(|py| {
# let fun = pyo3::wrap_pyfunction!(parse_int, py).unwrap();
# let value: usize = fun.call1(("5",)).unwrap().extract().unwrap();
# assert_eq!(value, 5);
# });
# }
```

When passed a string which doesn't contain a floating-point number, the exception raised will look like the below:
Expand Down Expand Up @@ -180,14 +188,15 @@ The following example demonstrates this for some imaginary third-party crate `so

```rust
# mod some_crate {
# struct OtherError(());
# pub struct OtherError(());
# impl OtherError {
# fn message() -> &'static str { "some error occurred" }
# pub fn message(&self) -> &'static str { "some error occurred" }
# }
# fn get_x() -> Result<i32, OtherError>
# pub fn get_x() -> Result<i32, OtherError> { Ok(5) }
# }

use pyo3::prelude::*;
use pyo3::exceptions::PyValueError;
use some_crate::{OtherError, get_x};

struct MyOtherError(OtherError);
Expand All @@ -210,6 +219,14 @@ fn wrapped_get_x() -> Result<i32, MyOtherError> {
let x: i32 = get_x()?;
Ok(x)
}

# fn main() {
# Python::with_gil(|py| {
# let fun = pyo3::wrap_pyfunction!(wrapped_get_x, py).unwrap();
# let value: usize = fun.call0().unwrap().extract().unwrap();
# assert_eq!(value, 5);
# });
# }
```


Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Expand Up @@ -453,6 +453,8 @@ pub mod doc_test {
"guide/src/faq.md" => guide_faq_md,
"guide/src/features.md" => guide_features_md,
"guide/src/function.md" => guide_function_md,
"guide/src/function/error_handling.md" => guide_function_error_handling_md,
"guide/src/function/signature.md" => guide_function_signature_md,
"guide/src/memory.md" => guide_memory_md,
"guide/src/migration.md" => guide_migration_md,
"guide/src/module.md" => guide_module_md,
Expand Down

0 comments on commit a549c55

Please sign in to comment.