AI-powered Python rewrite to Rust
May 12, 2026
When Python performance hits the wall, we can consider rewriting the compute-intensive logic in Rust. Rewriting Python code to Rust by looking at the Python code and reimplementing it in Rust is cumbersome and error-prone. We can do better than that. This blog series looks at 4 essential steps for doing the rewrite faster and more confidently with AI:
- Part 1 - Ensure existing code is well tested
- Part 2 - Rewrite existing tests to contract tests and add a dummy Rust wrapper
- Part 3 - Build the Rust implementation
- Part 4 - Use property-based testing to ensure the same output from Rust and Python for any given input
You can find the repository with all examples here
In this series, we used Claude Code (or your favorite AI coding tool) to guide us through the steps. But we could do exactly the same thing even when writing all the code manually. This flow works in both cases because we clearly define our expectations and then iterate toward the final solution. In fact, the property-based tests in Part 4 caught a real Unicode indexing bug that all 37 contract tests missed. That's exactly the kind of subtle issue that slips through a manual rewrite.
The approach applies to other rewrites as well. You could follow the same steps to rewrite Python to Cython or C++. As long as there are direct Python bindings available, you'll be fine. So, next time you need to rewrite something from Python to another language, I suggest you revisit this series of posts.
All the techniques and approaches used in this series are covered in depth inside my Complete Python Testing Guide course. So if you want to learn them in depth, I encourage you to grab it.
As usual, feel free to reach out to me on X or LinkedIn if you have any questions.
Happy engineering!