
On 2021-09-29 10:11, Dominik Vilsmeier wrote:
Lambda functions that have a single parameter are a common thing, e.g. for "key" functions: `sorted(items, key=lambda x: x['key'])`. For these cases however, the rather long word "lambda" together with the repetition of the parameter name, results in more overhead than actual content (the `x['key']`) and thus makes it more difficult to read. This is also a difficulty for `map` and `filter` for example where there's lots of visual overhead when using a lambda function and hence it's difficult to read: `filter(lambda x: x > 0, items)` or `map(lambda x: f'{x:.3f}', items)`.
Hence the proposal is to add a new syntax via the new token `?`. For the examples above:
* `sorted(items, key=?['key'])` * `filter(? > 0, items)` * `map(f'{?:.3f}', items)`
The rules are simple: whenever the token `?` is encountered as part of an expression (at a position where a name/identifier would be legal), the expression is replaced by a lambda function with a single parameter which has that expression as a return value, where any instances of `?` are replaced by the name of that single parameter. For example:
* `?['key']` translates to `lambda x: x['key']` * `? > 0` translates to `lambda x: x > 0` * `f'{?:.3f}'` translates to `lambda x: f'{x:.3f}'` * `?*?` translates to `lambda x: x*x`
[snip] I'd prefer something like "x -> x" "x => x" as an equivalent to "lambda x: x": sorted(items, key=i -> i['key']) The advantage of using '->' is that it already exists. This has all been suggested before. There have also the suggestions of adding a None-coalesce operator '??', plus None-coalesce subscripting with '?[...]', etc, which would be Python's equivalent of the null-coalesce operator of some other languages.