Calling Rust from Python using PyO3
saidvandeklundert.net
saidvandeklundert.net
It used to be hard to do such transfers between rust and python using arrow but from v3 or v4, arrow implementation in rust started supporting the c data interface. Creating the array in rust and sending it to python might involve leaking a boxed object though
Check this out if you want to see how https://github.com/jhoekx/python-rust-arrow-interop-example/...
https://docs.rs/arrow/6.2.0/arrow/array/type.LargeStringArra...
As for performance, YMMV but I think it could be faster since storing a list of strings as a numpy array would involve padding. Arrow arrays can get away without padding
Took about one evening to plug it all together and get it running. The guide at pyo3.rs was really helpful and maturin to build binary packages just works. You pass in python types and they arrive as rust-native types. Makes writing code feel very native.
The result: https://github.com/Grollicus/pyttfwrap takes a string and splits it as it would wrap when rendered with a given TTF font. Most of the code is about keeping a reference to the loaded font as that's an expensive operation.
Was some great fun and I'm sure I'll use it some more.
It makes sense to combine the two and replace C in this.
For compiled languages: Rust is the best when you care about memory safety. C is the best when you care about performance/simplicity/portability. C++ is the best when you care about modularity, Assembly is the best when you care about lowlevel stuffs, ...
For interpreted languages: Python is the best for data science, Java is the best for entreprise, Javascript is the best for speed, ...
Each one have a use case where they are the best. And those use cases I listed above, are entirely subjectives and will never be the same from person to person.
If there was an objectively best language period, why would other languages exist?
My point was that if you don't care about safety, C/C++/ASM have good aspects too.
I can write a program without a single pointer in C, and it will be fast, small, and portable.
Java is used a lot in data science alongside Python. And Javascript also have bindings for Tensorflow and other libs. They are scripting languages able to call C code, by definition they are glue languages.
Wheelerof5te said Rust is becoming the "world's best *compiled, safe* language". You objected to this, but then only listed alternative languages which aren't in that group. You responded as if Wheelerof5te had claimed there was "an objectively best language period".
> They are scripting languages able to call C code, by definition they are glue languages.
If I say something like "world's best chef" then I mean the person who is best at being a chef. Not the world's best (most moral?) person who happens to also fulfill the definition of being a chef but may be pretty bad at cooking. I think the same was intended here for "best glue language" - best at being a glue language.
But I'm guessing what you meant to suppose here would be instead to do this for C++ and that's not going to happen, though it does for some reason seem to be a popular wish of C++ enthusiasts. C++ doesn't express the thing the borrow checker is er... checking. So you'd need to adjust the language, Stroustrup has some sketched proposals about that, but realistically they're years out even if the C++ community was enthusiastic which they are not.
Python is currently the easiest language to learn, has a plethoa of modules in it's standard library alone, plus a vast ocean of 3rd party libraries. From displaying cute cats inside your terminal, to large mathematical monoliths like numpy and scipy. Python has almost everything you need to build programs, minus the speed and easy distribution of executables.
Java is semi-compiled and too verbose to be a glue language.
Javascript is faster than Python, but is much more difficult to use efficiently. It's standard library is such a joke that I had to install a 3rd-party library just to use a input() equivalent.
Here's the thing, presumably you agree that "It's fast except that it never works" isn't actually fast. So in practice your high performance C ends up compromised by the reality that it must work, at least often, which constrains what you are confident to actually write because you already know you can't write over-complicated code correctly.
Languages like Rust (and C++) enable you to write much more complicated software that you still understand well enough to debug it. An efficient filter that might be a single line of Rust or C++ may take dozens of lines of C, or else several macro invocations that add invisible overhead of lines that are constructed by the pre-processor unseen by the programmer, yet still taint the shared namespace and semantics. As a result, while the Rust or C++ programmer feels free to chain say, six filters the equivalent C looks monstrous and you recoil from it, even though that's the efficient way to solve the problem you had.
The intuition that if it looks simpler it's faster is often wrong, the reason Godbolt (Compiler Explorer) exists is that Matt Godbolt was concerned about whether the C++ for-each loop results in the same fast machine code as a manual loop, or whether you might pay a price for the nicer syntax. You don't, and Matt's continued exploration of this sort of issue, plus his generosity in sharing the result with the world is why the site is there now.
But of course the nicer iterator loop (and there are a lot of examples like this) encourages you to choose more complicated solutions which are faster, because total cognitive load isn't so great as it would be in a less expressive language. As a result even though you could in principle write an equally high performance C program, actual C programmers would not do that.
Now, machines don't fear complexity, so one of the interesting results of WUFFS is that they produce C code which no human would ever write, but which has all the properties they guaranteed (e.g. memory safety but lots more) in their small interest domain, by "simply" using tremendous amounts of complexity. The unexpected effect of this is that WUFFS-the-library is very fast: Since the only possible mistakes are programs that either don't do what is required or don't compile, WUFFS programmers are freed to focus on very fast tight code for the library. Again, you could in theory have written that code in C, but you wouldn't because you're human and you can't handle that.
The thing about wuffs is that you can't single step through it and there is no ecosystem of libraries a wuffs programmer could use.
This is why a subset of python that shares design principles with Julia and Nim, but transpiles to Rust, Go or C++ is interesting. It's not hugely popular with those language communities (prefer coding natively in Julia or Nim), but the pytorch thread (https://news.ycombinator.com/item?id=29354474#29371641) explains why the ecosystem is important (harder to build).
Having said that the basic hello world wuffs example in py2many isn't working as well as I'd like it to, but it's close.
1. C++ uses the equivalent of an Arc in Rust, because it can't tell if that reference will be shared across threads. In Rust you can use an Rc and, if you ever need an Arc, it will tell you.
2. Rust's `&str[..]` is safe, C++'s string_view causes tons of UAFs, so string_view is used much less frequently whereas &str is ubiquitous in rust code. In general you can share stack space in Rust easily, even across threads, which is incredibly powerful.
I think the clear benefit str has is that it's built in from day one. So any code which doesn't use str but should isn't old code it's just bad code. In contrast if you've got a pile of C++ then nothing written before 2017 uses string_view because string_view did not exist, and so then much of what got written after 2017 also didn't use string_view because the old code didn't understand string_view.
Well, except for the fact that the JVM and OS is written in C, but you could swap out that JVM and OS for...
It seems like cargo does a lot of heavy lifting w.r.t. dependencies which Bazel does not like. Do you have to vendor your dependencies- and your dependencies dependencies. Ad infinitum.
There is cargo-raze which helps, but only if you’re making a rust library: not if you’re making a binary.
So maybe it works for this case.
I'm really hoping bzlmod helps in this case: https://www.youtube.com/watch?v=TxOCKtU39Fs
The story for external deps is indeed extremely painful right now.
Cargo raze should let you consume libraries you've imported in a rust_binary target, if that's what you're talking about. It's also possible, but slightly more annoying, to vendor the dependency tree if you need to rely on pulling from a local mirror.
I've also used it to import cargo binaries (i.e wasm-bindgen-cli) into a Bazel workspace -- it just makes the resulting target something like @raze_some_bin//:bin
The three big gotchas with this are:
- You need to name the rule the same as the module you've exported in Rust
- It creates a copy to get the naming right. You could write an actual rule instead of a macro that just makes a symlink with the right name for Python to pick it up.
- Since the macro just exposes a genrule and isn't a PyInfo provider, you need to add it in the data of the py_library/binary you intend to use it in. Again, could be fixed by an actual rule impl.
The teammate who did it had been using Rust only for a couple months and none of us had ever used PyO3. He got it done in just a couple days. I consider that an endorsement of the API they've built.
It's heavily macro-based, which does cause some confusion. But if you spend some time with their examples, finding the fast path isn't too tricky.
We're calling Rust from Python. Haven't tried it the other way around. Our use case was helped by the fact that we are just passing a String into Rust and letting Rust do all the heavy lifting. There's minimal back-and-forth.
I liked how PyO3 managed panics (they're just normal exceptions that can be caught on the Python side). I wasn't the one dealing with Maturin, but it seemed reasonable to get started with. I never enjoy introducing more tools into a build system, but this was relatively painless.
If I recall correctly, the bindings themselves are only like… thirty lines of code.
1. What happens if the Rust code is misbehaving, panicking, etc?
2. What's build support like for this?
I'd love to gut what little Python code I have left and use Rust.
2. Building Python extensions out of PyO3 code is easy with maturin: https://github.com/PyO3/maturin