Book Image

Speed Up Your Python with Rust

By : Maxwell Flitton
5 (2)
Book Image

Speed Up Your Python with Rust

5 (2)
By: Maxwell Flitton

Overview of this book

Python has made software development easier, but it falls short in several areas including memory management that lead to poor performance and security. Rust, on the other hand, provides memory safety without using a garbage collector, which means that with its low memory footprint, you can build high-performant and secure apps relatively easily. However, rewriting everything in Rust can be expensive and risky as there might not be package support in Rust for the problem being solved. This is where Python bindings and pip come in. This book will help you, as a Python developer, to start using Rust in your Python projects without having to manage a separate Rust server or application. Seeing as you'll already understand concepts like functions and loops, this book covers the quirks of Rust such as memory management to code Rust in a productive and structured manner. You'll explore the PyO3 crate to fuse Rust code with Python, learn how to package your fused Rust code in a pip package, and then deploy a Python Flask application in Docker that uses a private Rust pip module. Finally, you'll get to grips with advanced Rust binding topics such as inspecting Python objects and modules in Rust. By the end of this Rust book, you'll be able to develop safe and high-performant applications with better concurrency support.
Table of Contents (16 chapters)
1
Section 1: Getting to Understand Rust
5
Section 2: Fusing Rust with Python
11
Section 3: Infusing Rust into a Web Application

Constructing our own custom Python objects in Rust

In this final section, we will build a Python module in Rust that can be interacted with in the Python system as if it were a native Python object. To do this, we must follow these steps:

  1. Define a Python class with all our attributes.
  2. Define class static methods to process numbers.
  3. Define a class constructor.

Defining a Python class with the required attributes

To start our journey, we define our class in the src/class_module/fib_processor.rs file, as follows:

  1. To build our class, we need to import the required macros by running the following code:
    use pyo3::prelude::{pyclass, pymethods, staticmethod};
    use crate::fib_calcs::fib_number::fibonacci_number;
    use crate::fib_calcs::fib_numbers::fibonacci_numbers;

    Here, we are using the pyclass macro to define our Rust Python class. We then use pymethods and staticmethod to define methods attached to the class. We also use standard Fibonacci numbers to calculate...