Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

Python: accept keyword arguments under the original's names (#1412)

jakalijey9b53413c02eb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1f30f85f..8e6fe66f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -267,6 +267,10 @@
- PowerShell: a parameter typed `[decimal]`, `[uint64]` or `[ulong]` keeps its function in
PowerShell, with the reasons C# gives for the same types, instead of bridging it as `f64` or
`i64`. `[uint32]`, `[double]` and `[single]` bridge as before (#1341 by @jakalijey).
+- Python: a port takes each keyword argument under its name in the original. The package maps
+ `maxLen=5` and `N=2` to the binding's `max_len` and `n` before calling the native function,
+ where it raised `TypeError` in `shadow` and `new` mode. Parameters already in snake_case
+ generate the same code (#1379 by @jakalijey).
- Ruby: a method whose default names a constant (`sep = SEP`, `Core::SEP`, `DEFAULTS[:sep]`)
stays in Ruby with the reason, as PHP does: the wrapper and the shadow define the method outside
the original's module, where the constant raised `NameError`. Literal defaults are bridged as
diff --git a/src/codegen_py.rs b/src/codegen_py.rs
index ce3694c4..2d0bf595 100644
--- a/src/codegen_py.rs
+++ b/src/codegen_py.rs
@@ -839,6 +839,44 @@ pub fn lib_rs(m: &Manifest, api: &PortApi, modules: &Modules) -> String {
out
}
+/// Passes keyword arguments named as in the original (`maxLen=5`) under the binding's
+/// snake_case names (`max_len`), which PyO3 takes them by.
+const KEYWORDS_PY: &str = r#"
+def _keywords(fn, names):
+ import functools
+
+ @functools.wraps(fn)
+ def call(*args, **kwargs):
+ given = {}
+ for k, v in kwargs.items():
+ name = names.get(k, k)
+ if name in given:
+ raise TypeError(f"{fn.__name__}() got multiple values for argument '{k}'")
+ given[name] = v
+ return fn(*args, **given)
+
+ return call
+
+"#;
+
+/// The original's parameter names that the binding renamed, with the binding's name:
+/// `maxLen` -> `max_len`, `N` -> `n`. A name that is already snake_case is not listed.
+fn renamed_keywords(m: &Manifest, f: &PortFn) -> Vec<(String, String)> {
+ let Some(export) = m.exports.iter().find(|e| e.name == f.js_name) else {
+ return Vec::new();
+ };
+ export
+ .params
+ .iter()
+ .filter_map(|p| {
+ let binding = crate::bridge::snake_case(&p.name);
+ // PyO3 shows a raw identifier (`r#type`) without its `r#`.
+ let binding = binding.trim_start_matches("r#");
+ (binding != p.name).then(|| (p.name.clone(), binding.to_string()))
+ })
+ .collect()
+}
+
/// The wrapper package: imports `_native`, converting structured values.
pub fn package_init(m: &Manifest, api: &PortApi) -> String {
// Structured values are converted in Rust (`pyconv.rs`): every export is the native one.
@@ -848,6 +886,13 @@ pub fn package_init(m: &Manifest, api: &PortApi) -> String {
imported the original module.\"\"\"\n\nfrom . import _native\n{CODEC_PY}\n",
m.unit
);
+ if api
+ .functions
+ .iter()
+ .any(|f| !renamed_keywords(m, f).is_empty())
+ {
+ out.push_str(KEYWORDS_PY);
+ }
let mut names = Vec::new();
for f in &api.functions {
let (json_params, json_ret) = structured(f);
@@ -889,6 +934,19 @@ pub fn package_init(m: &Manifest, api: &PortApi) -> String {
json_ret = if json_ret { "True" } else { "False" }
);
}
+ let renamed = renamed_keywords(m, f);
+ if !renamed.is_empty() {
+ let map: Vec<String> = renamed
+ .iter()
+ .map(|(from, to)| format!("'{from}': '{to}'"))
+ .collect();
+ let _ = writeln!(
+ out,
+ "{name} = _keywords({name}, {{{}}})",
+ map.join(", "),
+ name = f.js_name
+ );
+ }
names.push(f.js_name.clone());
}
for c in &api.classes {
@@ -2104,6 +2162,108 @@ mod tests {
}
}
+ #[test]
+ fn a_keyword_argument_keeps_its_name_in_the_original() {
+ // `def pad(text, maxLen=3, N=0)`: PyO3 takes `max_len` and `n`, and a caller passes
+ // `maxLen=5`, so the package maps the original's names before calling `_native`.
+ let mut m = verdict_manifest();
+ let param = |name: &str| Param {
+ name: name.into(),
+ ts_type: "int".into(),
+ optional: true,
+ default: Some("3".into()),
+ ..Default::default()
+ };
+ m.exports = vec![ExportedFn {
+ name: "pad".into(),
+ file: "cc.py".into(),
+ line: 1,
+ params: vec![
+ Param {
+ name: "text".into(),
+ ts_type: "string".into(),
+ ..Default::default()
+ },
+ param("maxLen"),
+ param("N"),
+ ],
+ returns: "string".into(),
+ ..Default::default()
+ }];
+ let pad = PortFn {
+ js_name: "pad".into(),
+ rust_name: "pad".into(),
+ params: vec![
+ ("text".into(), "String".into()),
+ ("max_len".into(), "i64".into()),
+ ("n".into(), "i64".into()),
+ ],
+ ret: "String".into(),
+ fallible: true,
+ is_async: false,
+ };
+ let api = PortApi {
+ functions: vec![pad],
+ ..Default::default()
+ };
+ let init = package_init(&m, &api);
+ assert!(init.contains("def _keywords(fn, names):"), "{init}");
+ assert!(
+ init.contains(
+ "pad = _native.pad\npad = _keywords(pad, {'maxLen': 'max_len', 'N': 'n'})\n"
+ ),
+ "{init}"
+ );
+ // Names that are already snake_case generate the code they did.
+ let plain = package_init(
+ &verdict_manifest(),
+ &PortApi {
+ functions: vec![verdict_port()],
+ ..Default::default()
+ },
+ );
+ assert!(!plain.contains("_keywords"), "{plain}");
+ }
+
+ #[test]
+ fn a_keyword_given_under_both_names_is_refused() {
+ // `pad("a", maxLen=5, max_len=7)` names one parameter twice: the original raises
+ // TypeError, and the mapped call must not keep whichever came last.
+ let Some(python) = ["python3", "python"].into_iter().find(|p| {
+ std::process::Command::new(p)
+ .arg("--version")
+ .output()
+ .is_ok_and(|o| o.status.success())
+ }) else {
+ return;
+ };
+ let script = format!(
+ "{KEYWORDS_PY}\n\
+ def pad(text, max_len=3):\n return text * max_len\n\
+ pad = _keywords(pad, {{'maxLen': 'max_len'}})\n\
+ assert pad('a', maxLen=2) == 'aa'\n\
+ assert pad('a', max_len=2) == 'aa'\n\
+ for kwargs in ({{'maxLen': 5, 'max_len': 7}}, {{'max_len': 7, 'maxLen': 5}}):\n\
+ \x20 try:\n\
+ \x20 pad('a', **kwargs)\n\
+ \x20 except TypeError as e:\n\
+ \x20 assert 'multiple values' in str(e), e\n\
+ \x20 else:\n\
+ \x20 raise SystemExit('accepted ' + repr(kwargs))\n\
+ print('ok')\n"
+ );
+ let out = std::process::Command::new(python)
+ .args(["-c", &script])
+ .output()
+ .unwrap();
+ assert!(
+ out.status.success(),
+ "{}{}",
+ String::from_utf8_lossy(&out.stdout),
+ String::from_utf8_lossy(&out.stderr)
+ );
+ }
+
#[test]
fn registrations_name_the_crate_so_a_same_named_crate_cannot_shadow_them() {
let constructor = PortFn {