| Python | Rust | Lesson |
|---|
uv init hello | cargo new hello | Your first Rust project |
uv run hello | cargo run | Your first Rust project |
mypy src | cargo check | Your first Rust project |
# no build step | cargo build // program in target/debug/ | Your first Rust project |
pyproject.toml | Cargo.toml | Your first Rust project |
[project] | [package] | Your first Rust project |
dependencies = [] | [dependencies] | Your first Rust project |
def main(): ... | fn main() { } | Your first Rust project |
if __name__ == "__main__": main() | // not needed: Rust starts at main() | Your first Rust project |
.venv/ | target/ | Your first Rust project |
def greet(name: str) -> str: | pub fn greet(name: &str) -> String { | A tiny app: a function and a module |
return f"Hello, {name}!" | format!("Hello, {name}!") // last line, no ; | A tiny app: a function and a module |
# new file src/hello/greeting.py | // new file src/greeting.rs, plus "mod greeting;" in main.rs | A tiny app: a function and a module |
from hello.greeting import greet | use greeting::greet; | A tiny app: a function and a module |
greeting.greet("Ada") | greeting::greet("Ada") | A tiny app: a function and a module |
def _helper(): ... # private by convention | fn helper() { } // private unless pub | A tiny app: a function and a module |
print(greet("Ada")) | println!("{}", greet("Ada")); | A tiny app: a function and a module |
print("hi") | println!("hi"); | Hello, variables and mut |
print(f"{x} and {y}") | println!("{x} and {y}"); | Hello, variables and mut |
print(f"{x + 1}") | println!("{}", x + 1); | Hello, variables and mut |
print(repr(items)) | println!("{:?}", items); | Hello, variables and mut |
s = f"{x}!" | let s = format!("{x}!"); | Hello, variables and mut |
x = 5 | let x = 5; | Hello, variables and mut |
x = 5
x += 1 | let mut x = 5;
x += 1; | Hello, variables and mut |
n: int = 5 | let n: i32 = 5; | Hello, variables and mut |
MAX = 100 # by convention | const MAX: u32 = 100; | Hello, variables and mut |
# comment | // comment | Hello, variables and mut |
"""docstring""" | /// doc comment | Hello, variables and mut |
if __name__ == "__main__": | fn main() { } | Hello, variables and mut |
x = 5 · ratio = 0.5 | let x: i32 = 5; · let ratio: f64 = 0.5; | Numbers and strings |
n = 200 # 0..255 | let n: u8 = 200; | Numbers and strings |
big = 10_000_000_000 | let big: i64 = 10_000_000_000; | Numbers and strings |
i = len(items) # index type | let i: usize = items.len(); | Numbers and strings |
7 / 2 # 3.5 · 7 // 2 # 3 | 7.0 / 2.0 · 7 / 2 // 3, cuts toward zero | Numbers and strings |
float(x) · int(x) | x as f64 · x as i32 | Numbers and strings |
len(s) # characters | s.len() // bytes · s.chars().count() | Numbers and strings |
s.upper() · s.strip() | s.to_uppercase() · s.trim() | Numbers and strings |
sub in s · s.split(",") | s.contains(sub) · s.split(',') | Numbers and strings |
f"{a}!" · s += "!" | format!("{a}!") · s.push_str("!") | Numbers and strings |
s = "hi" | let s: &str = "hi"; // borrowed view · let mut s = String::from("hi"); // owned | Numbers and strings |
True · c = "x" | true · let c: char = 'x'; | Numbers and strings |
def add(a: int, b: int) -> int: | fn add(a: i32, b: i32) -> i32 { | Functions and expressions |
return a + b | a + b // last expression, no semicolon | Functions and expressions |
return x # early exit | return x; | Functions and expressions |
def f() -> None: | fn f() { // returns () | Functions and expressions |
def f(x, y=1): | no default args; write a second function or pass every value | Functions and expressions |
f(x=1, y=2) | f(1, 2) // no keyword arguments | Functions and expressions |
a if c else b | if c { a } else { b } | Functions and expressions |
value = 1 + 2 | let value = { 1 + 2 }; // a block is an expression | Functions and expressions |
f(1) # call | f(1); | Functions and expressions |
def main(): ... | fn main() { ... } | Functions and expressions |
lambda x: x * 2 | |x| x * 2 // closure, lesson 8 | Functions and expressions |
print(f(1)) | println!("{}", f(1)); | Functions and expressions |
if x > 0: | if x > 0 { | if, loops and ranges |
elif x == 0: | } else if x == 0 { | if, loops and ranges |
else: | } else { | if, loops and ranges |
if items: | if !items.is_empty() { | if, loops and ranges |
for i in range(5): | for i in 0..5 { | if, loops and ranges |
for i in range(1, 6): | for i in 1..=5 { | if, loops and ranges |
for i in range(0, 10, 2): | for i in (0..10).step_by(2) { | if, loops and ranges |
for i in range(5, 0, -1): | for i in (1..=5).rev() { | if, loops and ranges |
while n > 0: | while n > 0 { | if, loops and ranges |
while True: | loop { | if, loops and ranges |
break | break; | if, loops and ranges |
continue | continue; | if, loops and ranges |
nums = [1, 2, 3] | let nums = vec![1, 2, 3]; | Vec and HashMap |
nums = [] | let mut nums: Vec<i32> = Vec::new(); | Vec and HashMap |
nums.append(4) | nums.push(4); | Vec and HashMap |
len(nums) | nums.len() | Vec and HashMap |
nums.sort() | nums.sort(); | Vec and HashMap |
nums[1:3] | &nums[1..3] | Vec and HashMap |
x in nums | nums.contains(&x) | Vec and HashMap |
for x in nums: | for x in &nums { | Vec and HashMap |
d["a"] = 1 | d.insert("a", 1); | Vec and HashMap |
d.get("a") | d.get("a") // Some(v) or None | Vec and HashMap |
del d["a"] | d.remove("a"); | Vec and HashMap |
Counter(xs) | *counts.entry(x).or_insert(0) += 1; | Vec and HashMap |
[x * 2 for x in xs] | xs.iter().map(|x| x * 2).collect::<Vec<_>>() | Iterators and closures |
[x for x in xs if x > 0] | xs.iter().filter(|x| **x > 0).collect::<Vec<_>>() | Iterators and closures |
lambda x: x * 2 | |x| x * 2 | Iterators and closures |
def f(x):
print(x)
return x * 2 | |x| {
println!("{x}");
x * 2
} | Iterators and closures |
sum(xs) | let total: i32 = xs.iter().sum(); | Iterators and closures |
max(xs), min(xs) | xs.iter().max(), xs.iter().min() // Option, lesson 11 | Iterators and closures |
sum(1 for x in xs if x > 0) | xs.iter().filter(|x| **x > 0).count() | Iterators and closures |
for i, x in enumerate(xs): | for (i, x) in xs.iter().enumerate() { | Iterators and closures |
for x, y in zip(a, b): | for (x, y) in a.iter().zip(b.iter()) { | Iterators and closures |
any(x > 0 for x in xs) | xs.iter().any(|x| *x > 0) | Iterators and closures |
all(x > 0 for x in xs) | xs.iter().all(|x| *x > 0) | Iterators and closures |
reversed(xs) | xs.iter().rev() | Iterators and closures |
class Point:
def __init__(self, x, y):
self.x = x
self.y = y | struct Point {
x: i32,
y: i32,
} | Structs and impl |
p = Point(1, 2) | let p = Point::new(1, 2); | Structs and impl |
def total(self): | fn total(&self) -> i32 { | Structs and impl |
def add(self, k):
self.n += k | fn add(&mut self, k: i32) {
self.n += k;
} | Structs and impl |
p = Counter()
p.add(1) # changes p | let mut p = Counter::new();
p.add(1); | Structs and impl |
@staticmethod
@classmethod | fn origin() -> Self { // no self, call with Type::origin() | Structs and impl |
self.x | self.x | Structs and impl |
print(repr(p)) | #[derive(Debug)] + println!("{:?}", p); | Structs and impl |
a == b | #[derive(PartialEq)] + a == b | Structs and impl |
copy.copy(p) | p.clone() // needs #[derive(Clone)] | Structs and impl |
class Meters:
self.value = v | struct Meters(f64); // read with .0 | Structs and impl |
class Point: # importable from other files | pub struct Point { // visible to other files | Structs and impl |
class Status(Enum):
OPEN = "open" | enum Status {
Open,
} | Enums and match |
Status.OPEN | Status::Open | Enums and match |
Status.OPEN.name # "OPEN" | match status { Status::Open => "Open", ... } | Enums and match |
match x:
case 1: | match x {
1 => ... | Enums and match |
case 0: | 0 => ... | Enums and match |
case 1 | 2: | 1 | 2 => ... | Enums and match |
case 3 | 4 | 5 | 6 | 7 | 8 | 9: | 3..=9 => ... | Enums and match |
case n if n < 0: | n if n < 0 => ... | Enums and match |
case _: | _ => ... | Enums and match |
isinstance(s, Circle) | Shape::Circle(r) => ... | Enums and match |
result = describe(x) | let result = match x { ... }; | Enums and match |
def cents(self): # in the Enum class | impl Coin {
fn cents(&self) -> u32 { ... }
} | Enums and match |
x: Optional[int] = None | let x: Option<i32> = None; | Option instead of None |
x = 5 # may be None later | let x = Some(5); | Option instead of None |
if x is not None: | if let Some(v) = x { | Option instead of None |
if x is None: | if x.is_none() { | Option instead of None |
if x is not None: | if x.is_some() { | Option instead of None |
d.get(key, default) | map.get(&key).copied().unwrap_or(default) | Option instead of None |
x or 0 | x.unwrap_or(0) | Option instead of None |
x + 1 if x is not None else None | x.map(|v| v + 1) | Option instead of None |
if x is None:
return None | let v = x?; | Option instead of None |
assert x is not None # crashes | x.unwrap() // crashes | Option instead of None |
assert x is not None, "no user" | x.expect("no user") // crashes | Option instead of None |
match x:
case None: ... | match x {
Some(v) => ...,
None => ...,
} | Option instead of None |
try:
n = int(s)
except ValueError:
n = 0 | let n: i32 = s.parse().unwrap_or(0); | Result and ? instead of exceptions |
n = int(s) # may raise | let n: i32 = s.parse::<i32>()?; | Result and ? instead of exceptions |
raise ValueError("empty") | return Err(BadName::Empty); | Result and ? instead of exceptions |
x = f() # may raise | let x = f()?; | Result and ? instead of exceptions |
try:
print(f())
except ValueError as e:
print(e) | match f() {
Ok(v) => println!("{v}"),
Err(e) => println!("{e}"),
} | Result and ? instead of exceptions |
n = int(s) # crashes on bad input | let n: i32 = s.parse::<i32>().unwrap(); | Result and ? instead of exceptions |
n = int(s) # crashes, with a message | let n: i32 = s.parse().expect("need a number"); | Result and ? instead of exceptions |
raise RuntimeError("boom") | panic!("boom"); | Result and ? instead of exceptions |
def f() -> int: | fn f() -> Result<i32, ParseIntError> | Result and ? instead of exceptions |
def f() -> None: # may fail | fn f() -> Result<(), String> | Result and ? instead of exceptions |
x if x is not None else 0 | x.unwrap_or(0) | Result and ? instead of exceptions |
b = a # same list, two names | let b = a; // moved: a is unusable now | Ownership and borrowing |
b = a.copy() | let b = a.clone(); | Ownership and borrowing |
y = x # int | let y = x; // numbers are copied | Ownership and borrowing |
def f(items: list[int]): ... | fn f(items: &[i32]) { } | Ownership and borrowing |
def f(items: list[int]): ... # changes it | fn f(items: &mut Vec<i32>) { } | Ownership and borrowing |
def f(name: str): ... | fn f(name: &str) { } | Ownership and borrowing |
f(items) # might change it | f(&items) // can only read | Ownership and borrowing |
f(items) # changes it | f(&mut items) // may change | Ownership and borrowing |
# (no equivalent: Python has no pointers) | *n += 1; // change the value behind a &mut | Ownership and borrowing |
# garbage collector frees later | // freed at the owner's closing } | Ownership and borrowing |
class Dog: # duck typing | impl Describe for Dog { fn describe(&self) -> String { ... } } | Traits instead of duck typing |
class Describe(Protocol): ... | trait Describe { fn describe(&self) -> String; } | Traits instead of duck typing |
def show(item: Describe): | fn show(item: &impl Describe) | Traits instead of duck typing |
def show[T: Describe](item: T): | fn show<T: Describe>(item: &T) | Traits instead of duck typing |
class Base:
def describe(self):
return "base" | trait Describe {
fn describe(&self) -> String {
String::from("base")
}
} | Traits instead of duck typing |
def __str__(self): ... | impl std::fmt::Display for X { fn fmt(...) -> std::fmt::Result } | Traits instead of duck typing |
def __repr__(self): ... | #[derive(Debug)] // print with {:?} | Traits instead of duck typing |
def __eq__(self, other): ... | #[derive(PartialEq)] // a == b | Traits instead of duck typing |
copy.copy(x) | x.clone() // needs #[derive(Clone)] | Traits instead of duck typing |
hasattr(x, "describe") | T: Describe // checked at compile time | Traits instead of duck typing |
items = [Circle(), Square()] | let items: Vec<Box<dyn Shape>> = ...; | Traits instead of duck typing |
def __add__(self, other): ... | impl std::ops::Add for X { type Output = X; ... } | Traits instead of duck typing |
TypeError # at run time | error[E0308]: mismatched types | Reading compiler errors |
NameError # at run time | error[E0425]: cannot find value | Reading compiler errors |
AttributeError # at run time | error[E0599]: no method named ... found | Reading compiler errors |
x = 1
x = 2 # always allowed | error[E0384]: cannot assign twice to immutable variable | Reading compiler errors |
items.append(x) # always allowed | error[E0596]: cannot borrow as mutable | Reading compiler errors |
b = a # shares the list | error[E0382]: borrow of moved value | Reading compiler errors |
# change a list while looping over it | error[E0502]: cannot borrow as mutable because it is also borrowed as immutable | Reading compiler errors |
match x: # no case _ is fine | error[E0004]: non-exhaustive patterns | Reading compiler errors |
# duck typing fails at call time | error[E0277]: the trait bound ... is not satisfied | Reading compiler errors |
mypy app.py | cargo check // fast: errors only, no build | Reading compiler errors |
help(thing) | rustc --explain E0382 | Reading compiler errors |
sys.argv | std::env::args() // the program comes first, like argv[0] | Building and running a real program |
sys.argv[1] | env::args().nth(1) // an Option | Building and running a real program |
argparse / click | clap // a crate | Building and running a real program |
python main.py notes.txt | cargo run -- notes.txt | Building and running a real program |
open(path).read() | fs::read_to_string(&path) // a Result | Building and running a real program |
for line in sys.stdin: | for line in io::stdin().lines() { | Building and running a real program |
os.environ.get("NAME", "x") | env::var("NAME").unwrap_or(String::from("x")) | Building and running a real program |
print(msg, file=sys.stderr) | eprintln!("{msg}"); | Building and running a real program |
sys.exit(main()) | fn main() -> ExitCode { ... } | Building and running a real program |
sys.exit(2) | std::process::exit(2); | Building and running a real program |
# no build step | cargo run --release -- notes.txt | Building and running a real program |
two [project.scripts] | src/bin/stats.rs + cargo run --bin stats | Building and running a real program |
uv init shop | cargo new shop | Cargo in depth: dependencies and workspaces |
uv run shop | cargo run | Cargo in depth: dependencies and workspaces |
mypy . | cargo check | Cargo in depth: dependencies and workspaces |
pyproject.toml / uv.lock | Cargo.toml / Cargo.lock | Cargo in depth: dependencies and workspaces |
[project] dependencies = [...] | [dependencies] | Cargo in depth: dependencies and workspaces |
[dependency-groups] dev = [...] | [dev-dependencies] | Cargo in depth: dependencies and workspaces |
requires-python = ">=3.12" | rust-version = "1.85" | Cargo in depth: dependencies and workspaces |
"pydantic[email]~=2.0" | serde = { version = "1", features = ["derive"] } | Cargo in depth: dependencies and workspaces |
uv add requests | cargo add reqwest | Cargo in depth: dependencies and workspaces |
uv lock --upgrade | cargo update | Cargo in depth: dependencies and workspaces |
uv tree | cargo tree | Cargo in depth: dependencies and workspaces |
__main__.py / __init__.py | src/main.rs / src/lib.rs | Cargo in depth: dependencies and workspaces |
import shop.models # file found automatically | mod models; // declare the file, then use | Cargo in depth: dependencies and workspaces |
.venv/ __pycache__/ dist/ | target/ | Cargo in depth: dependencies and workspaces |
PyPI / Read the Docs | crates.io / docs.rs | Cargo in depth: dependencies and workspaces |
pytest | cargo test | Tests, builds and shipping |
pytest -k negative | cargo test negative | Tests, builds and shipping |
pytest -s | cargo test -- --nocapture | Tests, builds and shipping |
def test_add(): | #[test]
fn add_works() { } | Tests, builds and shipping |
assert a == b | assert_eq!(a, b); | Tests, builds and shipping |
assert ok | assert!(ok); | Tests, builds and shipping |
with pytest.raises(ValueError): ... | #[should_panic] // or assert!(r.is_err()); | Tests, builds and shipping |
"""Docstring. >>> add(2, 2)""" | /// Doc comment with a ``` code block | Tests, builds and shipping |
sphinx-build docs/ html/ | cargo doc --open | Tests, builds and shipping |
ruff format / ruff check | cargo fmt / cargo clippy | Tests, builds and shipping |
uv build | cargo build --release | Tests, builds and shipping |
uv publish | cargo publish | Tests, builds and shipping |
uv tool install ruff | cargo install ripgrep | Tests, builds and shipping |
# C extension module | pyo3 + maturin // Rust inside a wheel | Tests, builds and shipping |
import json | use serde_json; | Reading real code |
from .models import User | use crate::models::User; | Reading real code |
module.function() | module::function() | Reading real code |
def _helper(): ... # private by convention | fn helper() { } // private unless pub | Reading real code |
@dataclass | #[derive(Debug, Clone, PartialEq)] | Reading real code |
def __str__(self): ... | impl fmt::Display for Score { } | Reading real code |
raise ValueError("bad") | return Err("bad".into()); | Reading real code |
def f(x: T) -> T: # TypeVar | fn f<T>(x: T) -> T { } | Reading real code |
# (no equivalent) | fn f<'a>(x: &'a str) -> &'a str { } | Reading real code |
async def f(): await g() | async fn f() { g().await; } | Reading real code |
# many names, one object | Rc<T> / Arc<T> // shared ownership | Reading real code |
pyproject.toml / uv.lock | Cargo.toml / Cargo.lock | Reading real code |
uv add requests | cargo add reqwest | Reading real code |
python -m pytest | cargo test | Reading real code |
del x | drop(x); | Memory without a garbage collector |
def __del__(self): ... | impl Drop for X { fn drop(&mut self) { ... } } | Memory without a garbage collector |
# freed when the refcount reaches 0 | // freed at the owner's closing } | Memory without a garbage collector |
gc.collect() | // no garbage collector | Memory without a garbage collector |
b = a # same list, two names | let b = a; // moves the header, the items stay | Memory without a garbage collector |
b = a.copy() | let b = a.clone(); // new heap memory | Memory without a garbage collector |
class Node:
next: "Node | None" | struct Node { next: Option<Box<Node>> } | Memory without a garbage collector |
sys.getsizeof(x) | std::mem::size_of::<T>() | Memory without a garbage collector |
_ = make() # a normal name | let _ = make(); // dropped at once | Memory without a garbage collector |
a = b # any object, shared | let a = Rc::clone(&b); | Shared ownership: Rc, RefCell and Weak |
a is b | Rc::ptr_eq(&a, &b) | Shared ownership: Rc, RefCell and Weak |
sys.getrefcount(x) | Rc::strong_count(&x) | Shared ownership: Rc, RefCell and Weak |
obj.field = 1 # through any name | obj.borrow_mut().field = 1; // Rc<RefCell<T>> | Shared ownership: Rc, RefCell and Weak |
print(obj.field) | println!("{}", obj.borrow().field); | Shared ownership: Rc, RefCell and Weak |
weakref.ref(obj) | Rc::downgrade(&obj) // a Weak<T> | Shared ownership: Rc, RefCell and Weak |
ref() # the object or None | weak.upgrade() // Some(rc) or None | Shared ownership: Rc, RefCell and Weak |
gc.collect() # frees cycles | // no cycle collector: break cycles with Weak | Shared ownership: Rc, RefCell and Weak |
# threads share objects | Arc<Mutex<T>> // Rc<RefCell<T>> for threads | Shared ownership: Rc, RefCell and Weak |
threading.Thread(target=f).start() | let h = thread::spawn(move || f()); | Threads without a GIL |
t.join() | h.join().unwrap() // also gives the return value | Threads without a GIL |
lock = threading.Lock()
with lock:
count += 1 | let count = Mutex::new(0);
*count.lock().unwrap() += 1; | Threads without a GIL |
# the same object in many threads | let shared = Arc::clone(&data); // Arc<Mutex<T>> | Threads without a GIL |
with ThreadPoolExecutor() as pool: | thread::scope(|s| { s.spawn(...); }); | Threads without a GIL |
queue.Queue() | let (tx, rx) = mpsc::channel(); | Threads without a GIL |
q.put(x) | tx.send(x).unwrap(); | Threads without a GIL |
q.get() | rx.recv().unwrap() // or: for x in rx { } | Threads without a GIL |
# GIL: one thread runs Python at a time | // threads run in parallel; data races do not compile | Threads without a GIL |
json.dumps(obj, separators=(",", ":")) | serde_json::to_string(&obj)? | The crates you'll meet everywhere |
json.dumps(obj, indent=2) | serde_json::to_string_pretty(&obj)? | The crates you'll meet everywhere |
User(**json.loads(text)) | let user: User = serde_json::from_str(text)?; | The crates you'll meet everywhere |
@dataclass # or a pydantic model | #[derive(Serialize, Deserialize)] | The crates you'll meet everywhere |
Field(alias="userName") # pydantic | #[serde(rename = "userName")] | The crates you'll meet everywhere |
tags: list = field(default_factory=list) | #[serde(default)] | The crates you'll meet everywhere |
raise RuntimeError("...") from e | result.context("...")? // anyhow | The crates you'll meet everywhere |
except Exception as e: | fn main() -> anyhow::Result<()> | The crates you'll meet everywhere |
class NotFound(ShopError): ... | #[derive(Debug, Error)] enum ShopError { #[error("...")] NotFound } | The crates you'll meet everywhere |
raise BadQuantity() from e | BadQuantity(#[from] ParseIntError) // then ? converts | The crates you'll meet everywhere |
argparse.ArgumentParser() | #[derive(Parser)] struct Args { ... } | The crates you'll meet everywhere |
parser.add_argument("--times", type=int, default=1) | #[arg(long, default_value_t = 1)] times: u32 | The crates you'll meet everywhere |
parser.add_argument("--shout", action="store_true") | #[arg(long)] shout: bool | The crates you'll meet everywhere |
args = parser.parse_args() | let args = Args::parse(); | The crates you'll meet everywhere |
asyncio.run(main()) | #[tokio::main]
async fn main() { } | async/await vs asyncio |
async def f(): ... | async fn f() { } | async/await vs asyncio |
await f() | f().await | async/await vs asyncio |
await asyncio.sleep(0.5) | tokio::time::sleep(Duration::from_millis(500)).await; | async/await vs asyncio |
await asyncio.gather(a(), b()) | tokio::join!(a(), b()) | async/await vs asyncio |
task = asyncio.create_task(f()) | let handle = tokio::spawn(f()); | async/await vs asyncio |
await task | handle.await.unwrap() | async/await vs asyncio |
await asyncio.wait_for(f(), timeout=1) | tokio::time::timeout(Duration::from_secs(1), f()).await | async/await vs asyncio |
asyncio.wait(..., return_when=FIRST_COMPLETED) | tokio::select! { ... } | async/await vs asyncio |
await asyncio.to_thread(blocking) | tokio::task::spawn_blocking(blocking).await | async/await vs asyncio |
except asyncio.CancelledError: | // no exception: a dropped future just stops | async/await vs asyncio |
# a pure-Python module stats.py | src/lib.rs with #[pymodule] fn stats(...) | Rust inside Python with PyO3 |
def mean(values: list[float]) -> float: | #[pyfunction]
fn mean(values: Vec<f64>) -> f64 { | Rust inside Python with PyO3 |
def greet(name=None): | #[pyfunction]
#[pyo3(signature = (name=None))]
fn greet(name: Option<&str>) -> String { | Rust inside Python with PyO3 |
raise ValueError("no values") | return Err(PyValueError::new_err("no values")); | Rust inside Python with PyO3 |
def f() -> int: # may raise | fn f() -> PyResult<i64> { | Rust inside Python with PyO3 |
class Counter: | #[pyclass]
struct Counter { ... } | Rust inside Python with PyO3 |
def __init__(self, step=1): | #[new]
#[pyo3(signature = (step=1))]
fn new(step: i64) -> Self { | Rust inside Python with PyO3 |
@property
def count(self): ... | #[pyo3(get)]
count: i64, | Rust inside Python with PyO3 |
def __repr__(self): ... | fn __repr__(&self) -> String { | Rust inside Python with PyO3 |
list / dict / None | Vec<T> / HashMap<K, V> / Option<T> | Rust inside Python with PyO3 |
pip install -e . | maturin develop // again after every Rust change | Rust inside Python with PyO3 |
python -m build | maturin build --release | Rust inside Python with PyO3 |
all(p(c) for c in s) | s.chars().all(|c| p(c)) | Reading real projects: uv, ruff and pydantic-core |
next((x for x in xs if p(x)), None) | xs.iter().find(|x| p(x)) | Reading real projects: uv, ruff and pydantic-core |
x is not None and p(x) | x.is_some_and(|v| p(v)) | Reading real projects: uv, ruff and pydantic-core |
if x is None:
raise MyError() | x.ok_or_else(|| MyError::new())? | Reading real projects: uv, ruff and pydantic-core |
s.lower() == "yes" | s.eq_ignore_ascii_case("yes") | Reading real projects: uv, ruff and pydantic-core |
"A" <= c <= "Z" | matches!(c, b'A'..=b'Z') | Reading real projects: uv, ruff and pydantic-core |
def __exit__(self, *exc): ... | impl Drop for Guard { fn drop(&mut self) { ... } } | Reading real projects: uv, ruff and pydantic-core |
@classmethod
def from_str(cls, s): ... | impl FromStr for X { fn from_str(s: &str) -> Result<Self, Self::Err> { ... } } | Reading real projects: uv, ruff and pydantic-core |
"".join(parts) | let mut s = String::with_capacity(n); s.push(c); | Reading real projects: uv, ruff and pydantic-core |