pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

Constructors for `PyLong` and `PyInt`

Open a1phyr opened this issue 2 years ago • 10 comments

Most types in pyo3::types have helper methods to create them easily (examples: PyString::new, PyBool::new). Is there a reason why there is no such method for PyLong and PyInt or is it an overlook ? Could we imagine adding them ?

Being able to build python objects in an easy and type-safe manner is a real strength of pyo3, and having a hole here seems a bit weird.

a1phyr avatar Mar 11 '22 14:03 a1phyr

Thanks for the suggestion!

One thing that is tricky is deciding what this function should look like. Should it accept just a single integer type, or should it accept multiple types, via a trait?

Fwiw, I have used 0_u8.into_py(py) the one time I needed this. What is your use case for this?

mejrs avatar Mar 13 '22 20:03 mejrs

@mejrs if this is not being worked on happy to take it on?

bjohnnyd avatar Jun 04 '22 17:06 bjohnnyd

@mejrs if this is not being worked on happy to take it on?

Please do!

mejrs avatar Jun 04 '22 18:06 mejrs

@bjohnnyd are you still workin on it? @mejrs I've also noticed that PyFloat::new accepts only c_double aka f64. Perhaps, if PyLong needs a more generic approach, it might be implemented for PyFloat as well

iyakushev avatar Jul 11 '22 21:07 iyakushev

@iyakushev I have some local changes for a future PR, so yes working on it. Though some discussion on whether it should be:

  1. A generic implementation?
  2. If generic, should it be via a trait?

would be beneficial.

I can make a PR and we can move the discussion there, unless @mejrs thinks otherwise?

bjohnnyd avatar Jul 11 '22 22:07 bjohnnyd

as of now, is it possible to build rust functions that return Py<PyLong> without casting magic?

Trolldemorted avatar Aug 29 '23 16:08 Trolldemorted

Is there a workaround for this? I'm having a hard time to build a PyInt/PyLong object from rust numeric types.

nicoCalvo avatar Jan 27 '24 22:01 nicoCalvo

@nicoCalvo as @mejrs said, you can go the into_py route and then downcast. For interest, what to you need the PyLong object for?

birkenfeld avatar Jan 28 '24 05:01 birkenfeld

@birkenfeld Thanks. I solved with rust native usize and converting to float. I was working on a rust implementation of python's dictor lib: https://github.com/nicoCalvo/dicto_r/blob/v1.0/src/lib.rs#L265 Any comments/suggestions are very welcomed as these are my first steps with Pyo3 and have not so much experience with rust either.

nicoCalvo avatar Jan 28 '24 15:01 nicoCalvo

@nicoCalvo I have to admit I don't understand that code. What is the original type of inner_object?

birkenfeld avatar Jan 31 '24 12:01 birkenfeld