Top Related Projects
The Python programming language
MicroPython - a lean and efficient Python implementation for microcontrollers and constrained systems
Implementation of Python 3.x for .NET Framework that is built on top of the Dynamic Language Runtime.
Python for the Java Platform
PyPy is a very fast and compliant implementation of the Python language.
A JavaScript implementation of the Python virtual machine.
Quick Overview
RustPython is an implementation of the Python programming language written in Rust. It aims to provide a fully compatible Python interpreter that can be embedded in Rust applications, while also offering the ability to compile Python code to WebAssembly.
Pros
- Improved performance compared to CPython in certain scenarios
- Seamless integration with Rust projects and the ability to embed Python in Rust applications
- Potential for running Python in WebAssembly environments
- Strong memory safety guarantees inherited from Rust
Cons
- Not yet fully compatible with all Python libraries and features
- Smaller ecosystem and community compared to CPython
- May have slower development pace due to the complexity of implementing Python in Rust
- Performance may vary depending on the use case and may not always outperform CPython
Code Examples
- Basic usage of RustPython in a Rust application:
use rustpython_vm as vm;
fn main() {
vm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
let scope = vm.new_scope_with_builtins();
let code = vm.compile("print('Hello from RustPython!')", "example.py", vm::compiler::Mode::Exec, Default::default()).unwrap();
vm.run_code_obj(code, scope).unwrap();
});
}
- Evaluating a Python expression and getting the result in Rust:
use rustpython_vm as vm;
fn main() {
vm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
let scope = vm.new_scope_with_builtins();
let result: i32 = vm.eval("2 + 3", Some(scope)).unwrap().try_into_value(vm).unwrap();
println!("Result: {}", result);
});
}
- Defining a Rust function and exposing it to Python code:
use rustpython_vm as vm;
fn rust_function(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
vm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
let scope = vm.new_scope_with_builtins();
let func = vm.new_function("rust_function", rust_function);
scope.set_item("rust_function", func, vm).unwrap();
let code = vm.compile("result = rust_function(5, 7)\nprint(f'Result: {result}')", "example.py", vm::compiler::Mode::Exec, Default::default()).unwrap();
vm.run_code_obj(code, scope).unwrap();
});
}
Getting Started
To use RustPython in your Rust project:
-
Add the following to your
Cargo.toml
:[dependencies] rustpython-vm = "0.2.0"
-
Import and use RustPython in your Rust code:
use rustpython_vm as vm; fn main() { vm::Interpreter::without_stdlib(Default::default()).enter(|vm| { let scope = vm.new_scope_with_builtins(); let code = vm.compile("print('Hello, RustPython!')", "example.py", vm::compiler::Mode::Exec, Default::default()).unwrap(); vm.run_code_obj(code, scope).unwrap(); }); }
-
Build and run your project using
cargo run
.
Competitor Comparisons
The Python programming language
Pros of CPython
- Mature and stable implementation with extensive ecosystem support
- Highly optimized C code for performance-critical parts
- Comprehensive standard library and built-in modules
Cons of CPython
- Global Interpreter Lock (GIL) limits true multi-threading
- Memory management can be less efficient compared to Rust
- Slower execution speed for certain tasks compared to compiled languages
Code Comparison
CPython (C implementation):
static PyObject *
string_count(PyStringObject *self, PyObject *args)
{
Py_ssize_t count;
Py_ssize_t start = 0;
Py_ssize_t end = PY_SSIZE_T_MAX;
PyObject *sub_obj;
const char *str, *sub;
Py_ssize_t len, sub_len;
if (!PyArg_ParseTuple(args, "O|nn:count", &sub_obj, &start, &end))
return NULL;
RustPython (Rust implementation):
fn count(
zelf: PyObjectRef,
args: FuncArgs,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
let (sub, start, end) = match args.args.len() {
1 => (
args.bind(vm, ("sub",))?,
0,
zelf.str(vm)?.len(),
),
2 => {
let (sub, start): (PyObjectRef, isize) = args.bind(vm, ("sub", "start"))?;
(sub, start, zelf.str(vm)?.len())
},
MicroPython - a lean and efficient Python implementation for microcontrollers and constrained systems
Pros of MicroPython
- Mature project with extensive hardware support
- Optimized for microcontrollers and embedded systems
- Smaller memory footprint and faster startup time
Cons of MicroPython
- Limited subset of Python standard library
- Performance can be slower for complex operations
- Less suitable for general-purpose Python development
Code Comparison
MicroPython:
import machine
import time
led = machine.Pin(2, machine.Pin.OUT)
while True:
led.toggle()
time.sleep_ms(500)
RustPython:
import time
while True:
print("Hello, RustPython!")
time.sleep(1)
MicroPython's code example demonstrates its focus on hardware interaction, while RustPython's example shows a more general-purpose Python implementation. MicroPython provides low-level hardware access, whereas RustPython aims for broader Python compatibility.
RustPython offers the advantage of Rust's performance and safety features, potentially leading to better execution speed for certain operations. It also aims to be more compatible with CPython, making it suitable for a wider range of Python applications.
However, RustPython is a newer project with less maturity and may have fewer libraries specifically optimized for embedded systems compared to MicroPython.
Implementation of Python 3.x for .NET Framework that is built on top of the Dynamic Language Runtime.
Pros of IronPython3
- Seamless integration with .NET ecosystem and libraries
- Better performance for Windows-specific applications
- More mature and stable implementation
Cons of IronPython3
- Limited cross-platform support compared to RustPython
- Slower development pace and less active community
- Dependency on .NET framework
Code Comparison
IronPython3:
import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import MessageBox
MessageBox.Show("Hello from IronPython!")
RustPython:
import sys
print(f"Hello from RustPython! Running on {sys.platform}")
The IronPython3 example demonstrates its tight integration with .NET, allowing direct use of Windows Forms. RustPython, being more focused on cross-platform compatibility, showcases a simple print statement that works across different operating systems.
Both projects aim to implement Python in different languages (C# for IronPython3 and Rust for RustPython) with distinct goals. IronPython3 excels in .NET integration, while RustPython offers better cross-platform support and leverages Rust's performance and safety features.
Python for the Java Platform
Pros of Jython
- Mature project with longer history and established ecosystem
- Seamless integration with Java libraries and frameworks
- Better performance for certain Java-heavy workloads
Cons of Jython
- Limited support for newer Python features and libraries
- Slower development pace compared to RustPython
- Larger runtime size due to Java dependency
Code Comparison
Jython:
from java.util import ArrayList
list = ArrayList()
list.add("Hello")
list.add("World")
print(list)
RustPython:
my_list = ["Hello", "World"]
print(my_list)
The Jython example demonstrates its ability to directly use Java classes, while RustPython uses standard Python syntax. This highlights Jython's strength in Java interoperability, but also shows that RustPython provides a more familiar Python experience.
RustPython aims to be more compatible with CPython and focuses on performance and memory safety through Rust. It's actively developed and supports more recent Python features. However, it lacks Jython's mature Java integration capabilities.
Both projects have their merits, with Jython excelling in Java environments and RustPython offering a promising future for Python implementation in Rust.
PyPy is a very fast and compliant implementation of the Python language.
Pros of PyPy
- Mature project with extensive compatibility and optimization
- Just-in-time (JIT) compiler for significant performance improvements
- Large community and widespread adoption in production environments
Cons of PyPy
- Limited support for some C extensions and libraries
- Slower startup time compared to CPython
- Memory usage can be higher, especially for short-running scripts
Code Comparison
PyPy:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
RustPython:
fn factorial(n: i32) -> i32 {
if n == 0 {
1
} else {
n * factorial(n - 1)
}
}
While the Python code remains the same for both implementations, RustPython allows for optional type annotations in Rust-style syntax, potentially offering better performance and type safety.
PyPy focuses on optimizing Python code execution through its JIT compiler, while RustPython aims to implement Python in Rust, potentially offering better memory safety and easier integration with Rust ecosystems. PyPy is more mature and widely used, while RustPython is a newer project with growing potential for specific use cases and environments.
A JavaScript implementation of the Python virtual machine.
Pros of Batavia
- Written in JavaScript, allowing for easier web integration and broader developer accessibility
- Part of the BeeWare suite, offering a more comprehensive ecosystem for cross-platform development
- Focuses on running Python bytecode in the browser, potentially enabling more seamless web applications
Cons of Batavia
- Limited to running Python in web browsers, whereas RustPython aims for broader system-level integration
- May have performance limitations compared to RustPython's Rust implementation
- Less active development and smaller community compared to RustPython
Code Comparison
Batavia (JavaScript):
var vm = new batavia.VirtualMachine();
vm.run('print("Hello, Batavia!")');
RustPython (Rust):
use rustpython_vm as vm;
vm::Interpreter::without_stdlib(Default::default()).enter(|vm| {
vm.run_code_obj(vm.compile("print('Hello, RustPython!')", "<embedded>", vm::compiler::Mode::Exec).unwrap(), vm.new_scope_with_builtins()).unwrap();
});
Both projects aim to implement Python in different languages, but their approaches and use cases differ. Batavia focuses on running Python in web browsers, while RustPython provides a more comprehensive Python implementation in Rust, potentially offering better performance and system-level integration.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME

RustPython
A Python-3 (CPython >= 3.12.0) Interpreter written in Rust :snake: :scream: :metal:.
Usage
Check out our online demo running on WebAssembly.
RustPython requires Rust latest stable version (e.g 1.67.1 at February 7th 2023). If you don't currently have Rust installed on your system you can do so by following the instructions at rustup.rs.
To check the version of Rust you're currently running, use rustc --version
. If you wish to update,
rustup update stable
will update your Rust installation to the most recent stable release.
To build RustPython locally, first, clone the source code:
git clone https://github.com/RustPython/RustPython
Then you can change into the RustPython directory and run the demo (Note: --release
is
needed to prevent stack overflow on Windows):
$ cd RustPython
$ cargo run --release demo_closures.py
Hello, RustPython!
Or use the interactive shell:
$ cargo run --release
Welcome to rustpython
>>>>> 2+2
4
NOTE: For windows users, please set RUSTPYTHONPATH
environment variable as Lib
path in project directory.
(e.g. When RustPython directory is C:\RustPython
, set RUSTPYTHONPATH
as C:\RustPython\Lib
)
You can also install and run RustPython with the following:
$ cargo install --git https://github.com/RustPython/RustPython
$ rustpython
Welcome to the magnificent Rust Python interpreter
>>>>>
If you'd like to make https requests, you can enable the ssl
feature, which
also lets you install the pip
package manager. Note that on Windows, you may
need to install OpenSSL, or you can enable the ssl-vendor
feature instead,
which compiles OpenSSL for you but requires a C compiler, perl, and make
.
OpenSSL version 3 is expected and tested in CI. Older versions may not work.
Once you've installed rustpython with SSL support, you can install pip by running:
cargo install --git https://github.com/RustPython/RustPython --features ssl
rustpython --install-pip
You can also install RustPython through the conda
package manager, though
this isn't officially supported and may be out of date:
conda install rustpython -c conda-forge
rustpython
WASI
You can compile RustPython to a standalone WebAssembly WASI module so it can run anywhere.
Build
cargo build --target wasm32-wasi --no-default-features --features freeze-stdlib,stdlib --release
Run by wasmer
wasmer run --dir `pwd` -- target/wasm32-wasi/release/rustpython.wasm `pwd`/extra_tests/snippets/stdlib_random.py
Run by wapm
$ wapm install rustpython
$ wapm run rustpython
>>>>> 2+2
4
Building the WASI file
You can build the WebAssembly WASI file with:
cargo build --release --target wasm32-wasi --features="freeze-stdlib"
Note: we use the
freeze-stdlib
to include the standard library inside the binary. You also have to run oncerustup target add wasm32-wasi
.
JIT (Just in time) compiler
RustPython has a very experimental JIT compiler that compile python functions into native code.
Building
By default the JIT compiler isn't enabled, it's enabled with the jit
cargo feature.
cargo run --features jit
This requires autoconf, automake, libtool, and clang to be installed.
Using
To compile a function, call __jit__()
on it.
def foo():
a = 5
return 10 + a
foo.__jit__() # this will compile foo to native code and subsequent calls will execute that native code
assert foo() == 15
Embedding RustPython into your Rust Applications
Interested in exposing Python scripting in an application written in Rust,
perhaps to allow quickly tweaking logic where Rust's compile times would be inhibitive?
Then examples/hello_embed.rs
and examples/mini_repl.rs
may be of some assistance.
Disclaimer
RustPython is in development, and while the interpreter certainly can be used in interesting use cases like running Python in WASM and embedding into a Rust project, do note that RustPython is not totally production-ready.
Contribution is more than welcome! See our contribution section for more information on this.
Conference videos
Checkout those talks on conferences:
Use cases
Although RustPython is a fairly young project, a few people have used it to make cool projects:
- GreptimeDB: an open-source, cloud-native, distributed time-series database. Using RustPython for embedded scripting.
- pyckitup: a game engine written in rust.
- Robot Rumble: an arena-based AI competition platform
- Ruff: an extremely fast Python linter, written in Rust
Goals
- Full Python-3 environment entirely in Rust (not CPython bindings)
- A clean implementation without compatibility hacks
Documentation
Currently along with other areas of the project, documentation is still in an early phase.
You can read the online documentation for the latest release, or the user guide.
You can also generate documentation locally by running:
cargo doc # Including documentation for all dependencies
cargo doc --no-deps --all # Excluding all dependencies
Documentation HTML files can then be found in the target/doc
directory or you can append --open
to the previous commands to
have the documentation open automatically on your default browser.
For a high level overview of the components, see the architecture document.
Contributing
Contributions are more than welcome, and in many cases we are happy to guide contributors through PRs or on Discord. Please refer to the development guide as well for tips on developments.
With that in mind, please note this project is maintained by volunteers, some of the best ways to get started are below:
Most tasks are listed in the issue tracker. Check issues labeled with good first issue if you wish to start coding.
To enhance CPython compatibility, try to increase unittest coverage by checking this article: How to contribute to RustPython by CPython unittest
Another approach is to checkout the source code: builtin functions and object methods are often the simplest and easiest way to contribute.
You can also simply run ./whats_left.py
to assist in finding any unimplemented
method.
Compiling to WebAssembly
Community
Chat with us on Discord.
Code of conduct
Our code of conduct can be found here.
Credit
The initial work was based on windelbouwman/rspython and shinglyu/RustPython
Links
These are some useful links to related projects:
- https://github.com/ProgVal/pythonvm-rust
- https://github.com/shinglyu/RustPython
- https://github.com/windelbouwman/rspython
License
This project is licensed under the MIT license. Please see the LICENSE file for more details.
The project logo is licensed under the CC-BY-4.0 license. Please see the LICENSE-logo file for more details.
Top Related Projects
The Python programming language
MicroPython - a lean and efficient Python implementation for microcontrollers and constrained systems
Implementation of Python 3.x for .NET Framework that is built on top of the Dynamic Language Runtime.
Python for the Java Platform
PyPy is a very fast and compliant implementation of the Python language.
A JavaScript implementation of the Python virtual machine.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot