Rust in Python: Perfect Balance of Performance and Productivity

<p>Python and Rust are two of the most beloved languages in software development where Python is known for its simplicity and productivity and Rust is famous for its performance and system control. Developing features in Python is very fast but it leads to mediocre performance for performance intensive tasks. While Rust is known for its performance intensive tasks but development in Rust is not that easy and fast. To get both, getting high performance for specific tasks and keeping development speed fast enough, we can develop performance critical tasks in Rust and all other code in Python. For this, we just need some way to call Rust functions in Python and that we will explore in this blog. This blog consists of a step by step guide to create Rust functions which are callable from Python and we will create simple arithmetic operations in Rust which will be callable from Python in this blog for sample code (The whole code can be found in a repo at&nbsp;<a href="https://github.com/sineshashi/Rust-From-Python" rel="noopener ugc nofollow" target="_blank">https://github.com/sineshashi/Rust-From-Python</a>&nbsp;).</p> <p><img alt="" src="https://miro.medium.com/v2/resize:fit:630/1*KqZ0foonHNLKRqYsbhLcxw.jpeg" style="height:467px; width:700px" /></p> <p>Cargo (Source: pexels.com)</p> <h2>Setting up a Cargo Project</h2> <p>First step is quite obvious, if we want to write code in Rust, we will create a new project with the help of Cargo by using the following command:</p> <pre> cargo new arithmetic_operations</pre> <p>Once we run it, we get a very important file&nbsp;<code>cargo.toml</code>&nbsp;which we will edit. In dependencies, we will need to add&nbsp;<code>pyo3</code>&nbsp;(This is the library which we will be using to achieve the feat of calling Rust functions from Python) with&nbsp;<code>extension-module</code>&nbsp;and add one more section of&nbsp;<code>lib</code>&nbsp;where we will set&nbsp;<code>type</code>&nbsp;to&nbsp;<code>cdylib</code>&nbsp;and our&nbsp;<code>cargo.toml</code>&nbsp;will like something like this:</p> <p><a href="https://medium.com/@shashikantrbl123/rust-in-python-perfect-balance-of-performance-and-productivity-def50440178d">Visit Now</a></p>
Tags: Python Cargo