pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

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

Open fsh opened this issue 4 years ago • 1 comments

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?

fsh avatar Oct 09 '21 16:10 fsh

Thanks, yes I agree there's some improvements that can be done here. It might be nice to remove the T: PyClass constraint on PyRef if possible (and only use the bound where it's relevant).

davidhewitt avatar Oct 13 '21 22:10 davidhewitt