Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

python: port @staticmethods

Mohit Mishra0dbf8960de01
diff --git a/README.md b/README.md
index 1ab0796..6a8c11d 100644
--- a/README.md
+++ b/README.md
@@ -97,7 +97,7 @@ fast-anything ports the outermost loop it can, not the tiny function called insi
| C and C++ (gcc or clang: `clang -O2 main.c lib.c`) | the same C bridge, through LoadLibrary or dlopen | ✅ |
| C# / .NET 8+ (`dotnet run -c Release`) | the same C bridge, through NativeLibrary; profiled with EventPipe, nothing to install | ✅ |
-It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`). In Java, C# and PHP that means static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.
+It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`). In Python that means module-level functions and `@staticmethod`s, in Java, C# and PHP static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.
Ruby, Java, Go, PHP, C, C++ and C# need no headers, bindings or extra tools: the port is a plain Rust library with one C entry point taking and returning JSON, and fast-anything replays the recorded calls against it directly. Any language that can call C can use that bridge.
diff --git a/src/hotspot.rs b/src/hotspot.rs
index b36d9c9..438c333 100644
--- a/src/hotspot.rs
+++ b/src/hotspot.rs
@@ -46,6 +46,7 @@ pub struct Hotspot {
/// and saves a Python/JS -> Rust crossing per call.
pub covered_by: Option<String>,
/// Ruby: the module (or Object) whose method this is, as a Ruby expression.
+ /// Python: the class of a @staticmethod.
pub owner: Option<String>,
}
diff --git a/src/python.rs b/src/python.rs
index b650063..04a72e9 100644
--- a/src/python.rs
+++ b/src/python.rs
@@ -92,7 +92,7 @@ pub fn record(
) -> Result<Recording> {
let module = hs.module.as_deref().context("this function can't be imported")?;
let meta = out.with_extension("meta.json");
- let job = json!({ "module": module, "func": hs.name, "out": out, "meta": meta, "limit": limit });
+ let job = json!({ "module": module, "func": hs.name, "owner": hs.owner, "out": out, "meta": meta, "limit": limit });
if module != "__main__" {
helper(ctx, python, "record", job, app_args)?;
} else {
@@ -104,8 +104,13 @@ pub fn record(
fs::create_dir_all(&backup_dir)?;
let backup = backup_dir.join(crate::util::slug(&hs.file));
fs::write(&backup, &original)?;
- let f = &hs.name;
- let wrap = format!("try:\n {f} = __fast_anything_wrap__({f})\nexcept NameError:\n pass");
+ let wrap = match hs.owner.as_deref() {
+ Some(cls) => format!(
+ "try:\n {cls}.{f} = staticmethod(__fast_anything_wrap__({cls}.{f}))\nexcept NameError:\n pass",
+ f = hs.name
+ ),
+ None => format!("try:\n {f} = __fast_anything_wrap__({f})\nexcept NameError:\n pass", f = hs.name),
+ };
fs::write(&file, backend::insert_marked(&original, "#", &format!("recording {}", hs.id), &wrap, main_guard))?;
let run = helper(ctx, python, "record", job, app_args);
fs::write(&file, &original)
@@ -437,7 +442,7 @@ pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
let job = json!({
"base": ctx.base_dir(), "libdir": ctx.lib_dir(), "ext": port.ext, "module": port.module,
"module_file": ctx.root.join(&port.file),
- "func": port.func, "cases": dir.join("recordings.jsonl"), "out": out, "budget": 0.5,
+ "func": port.func, "owner": port.owner, "cases": dir.join("recordings.jsonl"), "out": out, "budget": 0.5,
});
helper(ctx, python, "verify", job, &[])?;
let mut v: Verify = serde_json::from_str(&fs::read_to_string(&out)?).context("reading verify results")?;
@@ -465,7 +470,10 @@ pub fn shim(port: &Port, lib_rel: &str) -> String {
" except ImportError:",
" return None",
&format!(" return {f}"),
- &format!("{f} = _fast_anything_load() or {f}"),
+ &match port.owner.as_deref() {
+ Some(cls) => format!("{cls}.{f} = staticmethod(_fast_anything_load() or {cls}.{f})"),
+ None => format!("{f} = _fast_anything_load() or {f}"),
+ },
"del _fast_anything_load",
]
.join("\n")
@@ -534,6 +542,44 @@ mod tests {
}
}
+ #[test]
+ fn shim_for_a_static_method() {
+ let port = Port { owner: Some("Text".into()), ..port() };
+ let on = add_shim("class Text:\n pass\n", &port, ".fast/lib");
+ assert!(on.contains("Text.levenshtein = staticmethod(_fast_anything_load() or Text.levenshtein)"), "{on}");
+ assert_eq!(strip_shim(&on, "fuzzy.levenshtein"), "class Text:\n pass\n");
+ }
+
+ #[test]
+ fn static_methods_are_portable() {
+ let Some(python) = ["python3", "python"]
+ .into_iter()
+ .find(|p| Command::new(p).arg("--version").output().is_ok_and(|o| o.status.success()))
+ else {
+ eprintln!("no python on PATH, skipping");
+ return;
+ };
+ let dir = std::env::temp_dir().join(format!("fa-static-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(dir.join("runner.py"), RUNNER).unwrap();
+ fs::write(
+ dir.join("text.py"),
+ "class Text:\n @staticmethod\n def lev(a: str, b: str) -> int:\n return 0\n\n def size(self) -> int:\n return 0\n",
+ )
+ .unwrap();
+ let check = "import runpy, sys, os\n\
+ d = sys.argv[1]\n\
+ describe = runpy.run_path(os.path.join(d, 'runner.py'))['describe']\n\
+ f = os.path.join(d, 'text.py')\n\
+ info = describe(f, 3, 'lev', None, d)\n\
+ assert info['owner'] == 'Text' and info['blockers'] == [], info\n\
+ info = describe(f, 6, 'size', None, d)\n\
+ assert info['owner'] is None and info['blockers'], info\n";
+ let out = Command::new(python).args(["-I", "-c", check]).arg(&dir).output().unwrap();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ }
+
#[test]
fn maps_annotations() {
assert_eq!(rust_type("str", false).as_deref(), Some("&str"));
diff --git a/src/python/runner.py b/src/python/runner.py
index 30ded19..f203029 100644
--- a/src/python/runner.py
+++ b/src/python/runner.py
@@ -240,8 +240,11 @@ def describe(path, line, name, entry, base):
blockers.append("lives in the entry script, which runs on import: put that code under if __name__ == '__main__'")
elif module == "__main__" and node.lineno > guard:
blockers.append("defined inside the if __name__ == '__main__' block")
- if kind == "method":
- blockers.append("method (v0.1 ports module-level functions)")
+ owner = None
+ if kind == "method" and any(isinstance(d, ast.Name) and d.id == "staticmethod" for d in node.decorator_list):
+ owner = qualname.rsplit(".", 1)[0]
+ elif kind == "method":
+ blockers.append("method (module-level functions and @staticmethods only for now)")
elif kind == "nested":
blockers.append("nested function")
if isinstance(node, ast.AsyncFunctionDef):
@@ -308,6 +311,7 @@ def describe(path, line, name, entry, base):
"qualname": qualname,
"module": module,
"kind": kind,
+ "owner": owner,
"end_line": node.end_lineno,
"params": params,
"returns": returns,
@@ -432,7 +436,9 @@ def cmd_record(job, argv):
builtins.__fast_anything_wrap__ = wrap
else:
module = importlib.import_module(job["module"])
- setattr(module, job["func"], wrap(getattr(module, job["func"])))
+ owner = getattr(module, job["owner"]) if job.get("owner") else module
+ wrapped = wrap(getattr(owner, job["func"]))
+ setattr(owner, job["func"], staticmethod(wrapped) if job.get("owner") else wrapped)
run_target(kind, target, rest)
with open(job["out"], "w", encoding="utf-8") as f:
@@ -454,9 +460,10 @@ def cmd_verify(job, _argv):
entry = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = entry
spec.loader.exec_module(entry)
- original = getattr(entry, job["func"])
+ module = entry
else:
- original = getattr(importlib.import_module(job["module"]), job["func"])
+ module = importlib.import_module(job["module"])
+ original = getattr(getattr(module, job["owner"]) if job.get("owner") else module, job["func"])
with open(job["cases"], encoding="utf-8") as f:
cases = [json.loads(line) for line in f if line.strip()]