PyO3 / PyO3/pyo3

`#[derive(IntoPyObject)]` error a bit unhelpful when lifetime not called `'py`

Open
#4,704 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

In pydantic-core some (legacy) lifetimes were 'a instead of 'py, and using the new #[derive(IntoPyObject)] led to some interesting errors:

use pyo3::{Bound, IntoPyObject, PyAny};

#[derive(IntoPyObject)]
pub struct Wrap<'a>(Bound<'a, PyAny>);

gets lots of errors like

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'py` due to conflicting requirements
 --> src/lib.rs:3:10
  |
3 | #[derive(IntoPyObject)]
  |          ^^^^^^^^^^^^
  |
note: first, the lifetime cannot outlive the lifetime `'a` as defined here...
 --> src/lib.rs:4:17
  |
4 | pub struct Wrap<'a>(Bound<'a, PyAny>);
  |                 ^^
note: ...but the lifetime must also be valid for the lifetime `'py` as defined here...
 --> src/lib.rs:3:10
  |
3 | #[derive(IntoPyObject)]
  |          ^^^^^^^^^^^^
note: ...so that the types are compatible
 --> src/lib.rs:3:10
  |
3 | #[derive(IntoPyObject)]
  |          ^^^^^^^^^^^^
  = note: expected `pyo3::IntoPyObject<'py>`
             found `pyo3::IntoPyObject<'_>`
  = note: this error originates in the derive macro `IntoPyObject` (in Nightly builds, run with -Z macro-backtrace for more info)

changing the struct lifetime from 'a to 'py trivially resolves, though I wonder if there's any tricks we can do to improve the UX 🤔

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 reproducing the provided #[derive(IntoPyObject)] example with the lifetime named 'a rather than 'py. Inspect the IntoPyObject derive macro's diagnostic path and determine how its lifetime error is presented. Done means the reported error gives more useful guidance for this case without breaking the existing derive behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.