PyO3 / PyO3/pyo3

Possible ergonomics (or better documentation) opportunities for #[derive(FromPyObject)]

Open
#1,903 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

I was struggling a while to get something like this to work:

// Union-type for arguments to arithmetic operations.
#[derive(FromPyObject)]
pub enum IntOrElemArg<'a,T> {
  Obj(&'a T), // intended to be Self
  ZZ(&'a PyZZ), // another #[pyclass]
  Literal(RugInteger), // RugInteger implements FromPyObject
}

This naive approach failed for me. Maybe there is a way to get it to work, but I didn't find it. I finally figured out I need to change it to be:

#[derive(FromPyObject)]
pub enum IntOrElemArg<'a,T> {
  Obj(T),
  ZZ(PyRef<'a,PyZZ>),
  Literal(RugInteger),
}

impl<'a,T: PyClass> IntOrElemArg<'a,PyRef<'a,T>> { ... }

And can then only use it as IntOrElemArg<PyRef<Self>>. Putting PyRef<'a,T> into the enum directly there doesn't seem to be a way to indicate to the proc-macro that T: PyClass because the struct-constraint on PyRef infects upward?

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 file or test is named in the issue. Start by reproducing the two #[derive(FromPyObject)] enum forms and reviewing the derive behavior for PyRef, PyClass, and generic bounds; done means either a workable ergonomic approach is identified or the limitation and workaround are documented.

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
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.