Syntactic sugar to encourage use of named arguments

Sometimes I feel like we compare things to Rust too often, but there is a comparable feature in that language. Creating a struct is “keyword-only” unless you are passing in something with the same name as the field.

struct User {
    name: String,
    admin: bool,
}

...

let name = "James".to_string();
let a_user = User { name, admin: false };

I actually like this version, but it relies on the fact that Rust has much stricter rules.

I could imagine this for Python functions[1], but it is not backwards compatible because it reinterprets positional arguments as possibly-keywords-if-the-name-matches. That said, I suspect that in a large number of cases that would be affected, it’s a mistake: someone wrote f(bar) but forgot that the signature is f(foo, bar) and they intended f(bar=bar). Or they meant f(foo) but they named the variable bar because they forgot the signature (I do this in matplotlib all the time).

For anyone doing these big analyses of existing code, I’d be interested in knowing how often a positional argument is named the same thing as a different argument in the signature[2].


  1. perhaps just as a linter warning ↩︎

  2. not sure how you’d figure this out, though ↩︎

6 Likes