PyO3 / PyO3/pyo3

Function argument error handling improvements

Open
#1,055 8 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

This is a sketch of ideas for a follow-up of #1050 to enable #[pyfunction] (and #[pymethods] etc.) to report better errors for function inputs.

Imagine that the following #[pyfunction]:

#[pyfunction]
fn foo(tup: (i32, &str)) {
    println!("{:?}", tup)
}

After #1050, the error message when calling this function with invalid arguments is already much improved from PyO3 0.11.1:

>>> foo(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert None to PyTuple

I think that this error message can yet be improved further. There's two ways in which I'd like to see this improve:

  1. Mention the argument which failed to convert.
    Naming the function argument which failed to convert will help users locate exactly which function input is incorrect.

  2. Provide mypy-style type annotations for the target type, where possible.
    It's great to see that None can't convert to PyTuple, but as a Python user really what I need to see is that the expected type is Tuple[int, str].

Put together, this might mean that our foo function above would output error messages like the below:

>>> foo(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert None to `Tuple[int, str]` (when trying to extract argument `tup`)

I'm not super attached to the exact wording of the above if someone else has a better idea / something easier to implement.

Later today I'm going to add some thoughts on how these two pieces could be implented if anyone in the community is interested in championing these improvements.

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

Start by reading issue #1050 and the existing conversion and error-handling paths used by #[pyfunction] and #[pymethods]. Define how failed inputs should identify the argument and express the expected type, then confirm the behavior with relevant function-conversion tests. The issue is done when both improvements are implemented with agreed wording and covered by tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
api, backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.