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 @classmethods that don't use cls

Mohit Mishra1281e8cab84b
diff --git a/README.md b/README.md
index e7f6388..011957a 100644
--- a/README.md
+++ b/README.md
@@ -103,7 +103,7 @@ fast-anything ports the outermost loop it can, not the tiny function called insi
| C# / .NET 8+ (`dotnet run -c Release`) | the same C bridge, through NativeLibrary; profiled with EventPipe, nothing to install; GUIs and servers: `scan --duration 30` | ✅ |
| R 4.0+ (`Rscript app.R`) | the same C bridge, through base R's `.C()`; profiled with Rprof, no packages or R headers needed | ✅ |
-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`, or `if (import.meta.main)` / `if (require.main === module)`). In Python that means module-level functions and `@staticmethod`s (dataclasses, NamedTuples and numeric NumPy arrays count as plain data), 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.
+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`, or `if (import.meta.main)` / `if (require.main === module)`). In Python that means module-level functions, `@staticmethod`s and `@classmethod`s that don't use `cls` (dataclasses, NamedTuples and numeric NumPy arrays count as plain data), 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.
With Intel oneAPI on Windows, run fast-anything from a shell where `setvars.bat` ran (it sets up the linker). SYCL kernels run on the device and aren't ported; with `-fsycl`, only host functions are profiled and ported.
diff --git a/src/python.rs b/src/python.rs
index 12fe75f..cfab888 100644
--- a/src/python.rs
+++ b/src/python.rs
@@ -903,6 +903,37 @@ mod tests {
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
+ #[test]
+ fn class_methods_that_dont_use_cls_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-classmethod-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 LIMIT = 3\n\n @classmethod\n def lev(cls, a: str, b: str = 'x') -> int:\n return len(a) + len(b)\n\n @classmethod\n def capped(cls, a: str) -> int:\n return min(len(a), cls.LIMIT)\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, 5, 'lev', None, d)\n\
+ assert info['owner'] == 'Text' and info['blockers'] == [], info\n\
+ assert [(p['name'], p['default']) for p in info['params']] == [('a', None), ('b', \"'x'\")], info['params']\n\
+ info = describe(f, 9, 'capped', None, d)\n\
+ assert info['blockers'] == ['classmethod that uses cls (one that doesn\\'t can move)'], 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 static_methods_are_portable() {
let Some(python) = ["python3", "python"]
diff --git a/src/python/runner.py b/src/python/runner.py
index 3b496ac..853a0e4 100644
--- a/src/python/runner.py
+++ b/src/python/runner.py
@@ -556,10 +556,20 @@ def describe(path, line, name, entry, base):
elif module == "__main__" and node.lineno > guard:
blockers.append("defined inside the if __name__ == '__main__' block")
owner = None
- if kind == "method" and any(isinstance(d, ast.Name) and d.id == "staticmethod" for d in node.decorator_list):
+ decorators = {d.id for d in node.decorator_list if isinstance(d, ast.Name)}
+ drop_first = False # a classmethod's cls isn't an argument callers pass
+ if kind == "method" and "staticmethod" in decorators:
owner = qualname.rsplit(".", 1)[0]
+ elif kind == "method" and "classmethod" in decorators:
+ # one that never uses cls behaves like a staticmethod, for subclasses too
+ owner = qualname.rsplit(".", 1)[0]
+ first = (node.args.posonlyargs + node.args.args)[:1]
+ drop_first = bool(first)
+ cls = first[0].arg if first else None
+ if cls is None or any(isinstance(n, ast.Name) and n.id == cls for n in ast.walk(node)):
+ blockers.append("classmethod that uses %s (one that doesn't can move)" % (cls or "its class"))
elif kind == "method":
- blockers.append("method (module-level functions and @staticmethods only for now)")
+ blockers.append("method (module-level functions, @staticmethods and @classmethods only for now)")
elif kind == "nested":
blockers.append("nested function")
if isinstance(node, ast.AsyncFunctionDef):
@@ -630,6 +640,8 @@ def describe(path, line, name, entry, base):
positional = args.posonlyargs + args.args
defaults = [None] * (len(positional) - len(args.defaults)) + list(args.defaults)
+ if drop_first:
+ positional, defaults = positional[1:], defaults[1:]
params = [{"name": a.arg, "annotation": ast.unparse(a.annotation) if a.annotation else None,
"default": ast.unparse(d) if d is not None else None}
for a, d in zip(positional, defaults)]