PyO3 / PyO3/pyo3

Add PyResult::ok_or_is_instance_of method

Open
#4,819 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
16.2k
Forks
1k
Avg merge
2d 6h
Merged PRs (30d)
66

Description

A situation I repeatedly find myself in is wanting to handle one specific error type and raise all others. For example:

fn current_app(py: Python, request: &Option<Py<PyAny>>) -> PyResult<Py<PyAny>> {
    let none = py.None();
    let request = match request {
        None => return Ok(none),
        Some(request) => request,
    };
    match request.getattr(py, "current_app") {
        Ok(current_app) => return Ok(current_app),
        Err(e) if e.is_instance_of::<PyAttributeError>(py) => {}
        Err(e) => return Err(e),
    };
    let resolver_match = match request.getattr(py, "resolver_match") {
        Ok(resolver_match) => resolver_match,
        Err(e) if e.is_instance_of::<PyAttributeError>(py) => return Ok(none),
        Err(e) => return Err(e),
    };
    resolver_match.getattr(py, "namespace")
}

In this case, I think it could be more readable as:

fn current_app(py: Python, request: &Option<Py<PyAny>>) -> PyResult<Py<PyAny>> {
    let none = py.None();
    let request = match request {
        None => return Ok(none),
        Some(request) => request,
    };
    if let Ok(current_app) = request.getattr(py, "current_app").ok_or_isinstance_of::<PyAttributeError>(py)? {
         return Ok(current_app);
    }
    let resolver_match = match request.getattr(py, "resolver_match").ok_or_isinstance_of::<PyAttributeError>(py)? {
        Ok(resolver_match) => resolver_match,
        Err(_) => return Ok(none),
    };
    resolver_match.getattr(py, "namespace")
}

The main advantage of this, in my opinion, is that is avoids the boilerplate handling of Err(e) => return Err(e). When multiple such error handling blocks are adjacent, this adds up to a lot of unnecessary noise.

In my project, I can implement this as:

use pyo3::prelude::*;
use pyo3::type_object::PyTypeInfo;

trait PyResultMethods<T> {
    fn ok_or_isinstance_of<E>(self, py: Python<'_>) -> PyResult<PyResult<T>>
    where
        E: PyTypeInfo;
}

impl<T> PyResultMethods<T> for PyResult<T> {
    fn ok_or_isinstance_of<E>(self, py: Python<'_>) -> PyResult<PyResult<T>>
    where
        E: PyTypeInfo,
    {
        match self {
            Ok(obj) => Ok(Ok(obj)),
            Err(e) if e.is_instance_of::<E>(py) => Ok(Err(e)),
            Err(e) => Err(e)
        }
    }
}

but it might be useful enough to other PyO3 users to upstream.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No implementation files or tests are named. Start by locating the PyResult API and PyTypeInfo usage in the PyO3 source, then compare the proposed method's behavior with existing error-handling helpers; done means the method handles matching exceptions while propagating other errors and has coverage for those cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
backend-api-design
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.