- Podcasts
- CyberSecurity Summary
- Speed Up Your Python with Rust: Optimize Python performance by creating Python pip modules in Rust with PyO3
Speed Up Your Python with Rust: Optimize Python performance by creating Python pip modules in Rust with PyO3
CyberSecurity Summary
- September 22, 2025
- 44 min
About this episodeA technical guide published by Packt Publishing in 2021. It focuses on optimizing Python application performance by integrating Rust code…
You can listen and download our episodes for free on more than 10 different platforms:
https://linktr.ee/cyber_security_summary
Get the Book now from Amazon:
https://www.amazon.com/Speed-Your-Python-Rust-performance/dp/180181144X?&linkCode=ll1&tag=cvthunderx-20&linkId=9dfb7de39ff9edfb60f7009d47a3a55d&language=en_US&ref_=as_li_ss_tl
Discover our free courses in tech and cybersecurity, Start learning today:
https://linktr.ee/cybercode_academy
Transcript
From the publisherThis transcript comes from the podcast’s own feed, shown as the publisher wrote it.
Speed Up Your Python with Rust: Optimize Python performance by creating Python pip modules in Rust with PyO3
Our mission today is to unpack the practical art of fusing Python's legendary agility with rusts well unparalleled performance and safety. We're not just going to tell you how they work together. We'll explore why this combination can fundamentally revolutionize your approach to building efficient software.
Just vast exactly. It's flexible, object oriented programming is ideal for solving real world problems quickly. But here's the unavoidable truth, the double edged sword, uh huh, the speed. It's notoriously slow and not always the most efficient with system resources. This is where, especially with the explosion of big data and computationally intensive tasks, the need for faster, more performance languages becomes undeniable.
It's about achieving the best of both worlds. Really, the goal isn't to replace Python, not at all. It's about augmenting it. Okay, you use Python for what it excels at rapp development, complex high level logic, orchestrating your application, and then when you hit a performance bottleneck, you strategically reach.
Nope, this isn't just about being pedantic. This aggressive typing ensures a level of safety in the long run that Python's dynamic nature can't match, because it catches entire classes of bugs before your code even run that compile time exactly. Another immediate difference is that variables in Rust are automatically immutable by default. You have to explicitly declare them with MUTT if you intend to change their value.
Mostly kind of yeah, and unsigned integers you eight or U one twenty eight, which only old non negative numbers. This impacts their range. For example, you eight can hold zero two of fifty five. If you try to let braking number you eight equals two to fifty six, the compiler will simply tell you it doesn't fit Bam, compile error.
Statement match like a switch statement, similar but more powerful. This match statement is like a supercharged switch, but with a critical difference. The compiler forces you to handle every single possible outcome that your enom could represent, every single case, every single one. If you miss a case, it won't compile. This provides an incredibly robust safety net, ensuring you don't accidentally overlook a scenario. Wow, you can use the pattern like an underscore to catch any unhandled cases or values you genuinely don't care about, which keeps the compiler happy.
Superpower, right, yeah, it really is. Rust handles errors with a result type. It's a bit like Python's none for missing values may be, but much more explicit. How so, our result is a container that either holds an OK value meaning success and it contains the successful result, or an error value indicating that something went wrong, containing the error information.
So you have to deal with the possibility of an error exactly. It forces you to explicitly acknowledge and handle potential errors. But the real magic, the core of Rust's promise lies in its compile time memory protection. Rust's compiler is a vigilant guardian the borrow checker, that's the one. It aggressively checks your code to prevent a whole host of common, notoriously difficult to debug memory errors. We're talking about use after freeze.
Yes. Second, when that owner variable goes at a scope, like at the end of a function or block, the memory it occupies is automatically deallocated. You don't have to manage it manually automatic cleanup right, and Third, values can be used by other variables, but only if you adhere to very specific conventions. Copying moving, immutable borrowing, immutable borrowing.
You're giving someone exclusive access to that book so they can make changes. Only one mutable borrow can exist at a time, only one editor, and crucially, the original variable cannot be used at all, not read, not borrowed again while it's mutably borrowed, because its state might be altered unpredictably. This prevents conflicts and ensures data integrity.
Yes, it's a classic example. Imagine you declare a variable one outside of scope, then inside an interscope you create two and make one borrow a reference to two. Okay, when that interscope ends, two is dropped. Its memory is gone, but one still exists outside holding a reference to nothing, a dangling.
Rust allows for explicit lifetime annotations using syntax like a pike. These essentially let you tell the compiler, Hey, this reference I'm passing around will only be valid as long as this other piece of data it points to is valid. It helps manage complex borrowing scenarios across different parts of your code.
Okay, so Rust has these powerful, strict foundational principles, but how do you actually build something with it? What are the tools and architectural blueprints that make this robust, high performance code come to life? In Python? We have PIP and virtual and PIV. How does Rust handle its projects?
For Rust, Cargo is your single source of truth. It's the all in one tool that handles everything everything pretty much running your code, testing, generating documentation, building your binaries, managing your dependencies from creates dot io the Rust package registry. It's incredibly integrated.
What's wonderfully clean about Rust is its dot get ignore file. Typically it just contains target. That's it. Target. Yeah, because everything Cargo produces compile binaries, documentation Cach's intermediate files is neatly stored in that single directory. It keeps your project root very clean compared to Python's often sprawling cash files and build artifacts.
You can even use option F thirty two for optional parameters in your public functions and using self for methods that just read data rather than self, which takes ownership, is important for usability. This layered approach means internal refactoring is safer as long as the public interface stays the same. You don't break downstream code.
Okay, so, for packaging standard Python pitp modules, you typically start with a GitHub repository, use a dot godn or file again usually much smaller for Rust. Often just target within the Rust part and then can figure a setup dot pifile or more modernly piproject dot tom l with a build back end.
Yeah, this defines all your package metadata like the name, version, authors, and crucial dependencies via install requires installing. It is then as simple as pip installed, get plus https dot GitHub dot com, your dash repoy, your dat package at main or eventually pick install your package from PIPI.
There definitely a quick but important note. Traditionally, set up dot pi runs arbitrary code as your user potentially root during installation. Malicious code injected there can be a serious vector for attack. Modern builds with piproject dot com tomol can mitigate this somewhat. Also, always be wary of type A squadding accidentally installing Request instead of the popular Request library for example.
Potentially, Yes, if the specific type inconsistency doesn't cause an immediate crash. Mypile provides a fantastic layer of confidence and catches mini bugs early. But it's a lner an external tool that you runs. Hope system is a fundamental inescapable part of its compilation process right.
Can write Python code, perhaps using the request library to interact with the PIPIAPI to fetch the latest version number of your own package or dependency. This is incredibly useful for automated release processes, generating change logs, and ensuring your continuous deployment pipelines are always working with the correct intended versions.
You also need a hashtag PI module function to declare the Python module itself and add your halftag PI functions to it. PIO three handles all the complex glue code type conversions, air handling, mapping in the background. It makes it feel remarkably like Python is calling just another Python function even though it's running compiled rustcode under the hood.
When you put it all together, especially for raw performance, what's the big reveal? Like if you're calculating something computationally intensive like Fibonacci numbers, how does Rust even with PIO three bindings compared to pure Python or even number Numba tries to speed up Python two right.
Right Number is a just in time compiler for Python functions, often using LLVM. It can give significant speed ups. But this is where the jaws drop when you bring in Rust via PIO three. We ran a speed test for fibonacci calculation across pure Python, number and our new Rust module via PIO three bindings, and the results The results were astounding. The Rust class, even with the overhead of those PIO three bindings, translating between Python and RUSS types was a staggering forty three times faster than the pure Python class for calculating, say, the thirty fifth Vivonacci number forty three times forty three. While Number also provided a significant speed up, maybe ten to fifteen times faster than pure Python in our test, it comes with its own challenges. It can be notoriously difficult to install and get working reliably on certain systems. Like say in M one MAC, often requiring specific and pilot setups or environments.
That's a staggering difference. Forty three times faster. Okay, moving on from raw sequential speed. When you're dealing with complex systems, mastering concurrency with threads and processes becomes crucial. What's the fundamental difference between threads and processes? Especially for a Python developer dealing with the GIL, that's a key distinction.
Processes, on the other hand, are more expensive to create than three threads because they are independent entities managed by the operating system. They do not share memory by default, which makes them inherently safer for true parallelism, as each process gets its own Python interpreter and its own GIL.
Yes, a process can host multiple threads itself, but the key is that different processes run independently. While context switches between processes are more expensive for the OS, they're generally better for both CPU bound and ioheavy tasks in Python because they bypass the GIL limitation for parallelism.
Result is the standard ok or air for error handling. If the thread panics crashes. Join returns in air. Box means the error is allocated on the heat because its size might not be known at compile time. Any means the error could be dynamically of almost any type, and send is a marker trait indicating the error type is safe to transfer across thread boundaries.
If you're using it to demonstrate concurrency, be aware that the overhead of spinning up processes or even threads can easily outweigh any computational gains unless the number you're calculating is genuinely large, and you use techniques like memoization or caching to avoid recalculating redundant values. It's often a poor choice for benchmarking real world performance gains from concurrency.
By simply calling dot interperator on a collection like a VEC, you convert a standard iterator into a parallel iterator. You can then apply functions like map, filter, induced, etc. Just like normal iterators, but Rayon automatically parallelizes the work across a threadpool. Utilizing all available CPU.
Often it's close to that simple for basic data parallelism. For tasks like parallel FIBONACI calculations on a list of numbers, this approach can yield significantly better speed increases. We've seen it yield maybe a twenty percent or more speed up and RUST for appropriate tasks, compared to Python's multiprocessing, which might only give you a five percent gain for the same task, partly due to the GIL and pythons overheads.
Wanted to go even lower level in Rust without third party creates like Rayon, it involves manually using std dot process dot command to spawn new OS processes and explicitly managing their student and stood out pipes, perhaps using tools like buff reader to send data back and forth. It's much more manual.
Not infinitely better. No, if only say fifty percent of your task can actually be parallelized, even with infinite cores, you'll only ever get a two x speed up max. The formula speed up pull one one P plus PS illustrates this P is the parallelizable proportion. S is the speed up of that part. Performance will inevitably plateau based on the sequential portion. So throwing more hardware at a problem with inherent sequential bottlenecks won't help indefinitely.
Finally? Race conditions. These are probably the most common concurrency bug. They occur when multiple threads or processes try to access and modify shared data simultaneously without proper coordination. The final result depends unpredictably on the exact timing and interleaving of operations.
The big message is concurrency is hard. If it becomes overly complex to manage, or you're spending more time debugging deadlocks and race conditions than writing features. Then maybe simpler sequential programming is safer for that part of the system, or it's a strong sign that a fundamental design rethink is needed for your architecture. Don't introduce concurrency.
For the Docker file setup for your main class application service, you'll need to make sure you install the necessary build tools. That usually means things like Python three dev for Python c headers, maybe build essential or specifically GCC and the Rust tool chain itself, so you can compile your Rust extension module directly within the container image during the Docker build.
Yes, Crucially, it's good practice to initialize your database engine dB engine using squalkmmuse creen engine only once, perhaps as a singleton instance, and import that instance across your application. This helps avoid issues like too many dangling sessions or connection fool exhaustion.
Celery integrates nicely with the flask app context. You usually use a Makecelery factory function. This allows your background Selery tasks to access your flask apps configuration and extensions like the database session correctly. It lets you offload heavy, long running tasks like processing and upload or sending emails to background workers, significantly improving your web apps responsiveness for the user.
Back when you demonstrate this in a live web context, you might have two endpoints calling the Rust backed endpoints say Rust calculate dot number, you'll likely see it can be dramatically faster. We observed it being potentially four times faster or more for higher Fibonacci numbers. Compared to a Python calculate dot number endpoint, calling the pure Python logic for the same calculation, the difference becomes very apparent.
As we mentioned for the Docker file, you simply modify it to first install the Rust tool chain. These caimply using the official Rust upscript dot, curl, HTTPS, dot s dot, rust up dot r s SSFA, sy profile minimal, modify path, and then as part of your Python package installation staff like pipinstall dot the build back end set up tools Rust mature automatically compiles your Rust extension module within that Docker image before your application.
Yes, this involves configuring a Diesel dot com l file using the Diesel Cli tool to manage migrations, migration run and to introspect your database schema. Are generating RUSS code definitions for your tables into a schema dot r s file. There are even tools like Diesel x that can help autogenerate your database model strucks models dot rs from the schema.
Your Rust extension module can then directly perform complex queries or bulk operations against the database using Diesel, potentially much faster than going through Python and skoalcomy for certain tasks, and then expose just the final results back to your Python Flask application. This opens up even more possibilities for optimizing performance critical database interactions.
Pythons should remain your go to for high level tasks building the web application framework, general data manipulation, scripting, machine learning, where rapid development and its rich library ecosystem key. You should reserve rest for those specific identified critical performance bottlenecks, low level system programming, or areas where memory safety and explicit concurrency control are absolutely paramount Be strategic.
For instance, in a two D physics simulation, Rust could efficiently calculate all the coordinates of a trajectory maybe millions of points, and return that raw data, perhaps as a simple list dictionary, back to Python. Python would then consume those coordinates via an intuitive Python class or object, making it seamless and familiar for the Python user. They don't need to know the gritty details of the Rust.
Traits and Rust are super powerful. They define shared behavior for structs somewhat similar to interfaces in languages like Java or Go, or maybe conceptually like Python's abstract based classes ABC's. Combined with duct typing, they let you define capabilities like what For example, you could create speak, clinical skills, and advance medical traits in Rust. Then you implement these specific traits for different people's structs like patient maybe only implements speak, nurse implement speak and clinical skills or doctor implements.
Interestingly, when exposing Rust strucks that implement traits to Python using PIO three's hashtag et opi class, these trait implementations often translate very naturally into direct attributes or methods on the resulting Python class, making them immediately usable in a Pythonic way. For instance, the Advanced Medical trait might expose diagnose, and prescribe methods that become directly callable on the doctor Python object.
But as the data size and the computational load per item increase, for example calculating Fibonacci numbers up to thirty three or higher for a list of inputs, Rayon's benefits become immediately clear and substantial. It's about knowing when the overhead is worth the game profile your code.
You listening now hopefully have a much deeper understanding of how to leverage Python's rapid development cycle and rich ecosystem for your complex application logic, while surgically infusing the raw speed, reliability, and concurrency benefits of Rust into your most performance critical.
So here's the final thought. In a world drowning in data, where every millisecond can translate into real world impact or user satisfaction, how will this deeper understanding of Python and Rust influence your next architectural decision? How might you start to identify the hitting performance bottlenecks lurking in your current projects and strategically introduce Rust to truly turbocharge them, all while maintaining that developer friendly expert orian's Python is so famous for.
