PyO3 / PyO3/pyo3

`Python<'_>` is not a valid argument to `async #[pyfunction]`s

Open
#5,682 3 comments 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

The following code fails to compile:

#[pyfunction]
async fn none(py: Python<'_>) -> Bound<'_, PyAny> {
    py.None().into_bound(py)
}

The error message is:

error[E0521]: borrowed data escapes outside of function
 --> src/lib.rs:7:5
  |
7 |     #[pyfunction]
  |     ^^^^^^^^^^^^^
  |     |
  |     `py` is a reference that is only valid in the function body
  |     `py` escapes the function body here
  |     lifetime `'py` defined here
  |     argument requires that `'py` must outlive `'static`
  |
  = note: this error originates in the attribute macro `pyfunction` (in Nightly builds, run with -Z macro-backtrace for more info)

error: future cannot be sent between threads safely
  --> src/lib.rs:7:5
   |
 7 |     #[pyfunction]
   |     ^^^^^^^^^^^^^ future created by async block is not `Send`
   |
   = help: within `{async block@src/lib.rs:7:5: 7:18}`, the trait `Send` is not implemented for `*mut pyo3::Python<'static>`

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

Reproduce the failure in src/lib.rs using the shown async #[pyfunction] example, then trace the attribute macro's handling of Python<'_> arguments and its generated async wrapper. Done means the example compiles without the lifetime and Send errors and the relevant regression coverage passes.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
api, backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.