cffi vs cpython vs pyo3, what should I use?
Hi all, I've gotten to the stage in a project where I need to connect Python to my Rust. After some Googling, PyO3, cpython, and cffi seem to be the most mature ways of doing it, but I lack the experience in this area to make a sensible decision about which to use.
PyO3 seems pretty cool, but it requires the nightly toolchain and I'm not so sure I want to introduce a dependency on that to the company. Dev-ops is already trying to reel me in a bit and I'd rather not push it. cpython seems a bit less fleshed out, but at least (AFAICT) it'll build on stable... and I suspect both of these are using cffi under the hood, so one question is are they a good value or would I be better off skipping the middle layer?
Are there other gotchas I should be aware of? The answer to "what should I do" questions is typically "it depends.", and if that's the answer, what does it depend on?
Posted Apr 8, 2020, 8:33 PM UTC · edited
Spoiler: I use cpython a lot (I'm a Mercurial core dev that does most of the Rust work) and one of my colleagues is a maintainer.
I like cpython: it's well built, does not use any more unsafe that is needed, is getting frequent updates and might get a nicer interface (read: proc macros) once my colleague is a little bit less busy. It's used in production by Facebook for Mononoke : building on rust-stable is a must for any production-grade code IMO. Specialization is still a ways off from being stable, and - here comes more anecdotal evidence - I haven't heard as many people vouch for the soundness of PyO3 as cpython's.
I found a number of soundness problems in pyo3, and I think at least some of those might be relevant to cpython, but I didn’t look deep enough into cpython to tell.
A quick look tells that at least one of them is not a problem in cpython though – cpython is properly catches panics that are invoked in rust code (instead of propagating them into python).
I would be very interested to know if you find soundness issues in cpython! Good to know
Since you have experience with rust-cpython, maybe you know this: Is there a way to create a Python subclass in Rust? Specifically, I want to wrap a Rust enum into a Python enum with rust-cpython, but I cannot find a way to subclass Python's
Enumclass. Now I suspect that might just not be possible, but maybe I'm missing something?I'm almost sure this is not possible at this time. Your best best is to use composition, i.e. encapsulate your Rust logic in a Python class. You could go post an issue and get an answer from the maintainers.
Alright, thanks!