I'm new here, but I know that lambda expression
syntax has probably been discussed to oblivion. I have searched
previous posts without finding anything exactly like my idea so
here it is:
# instead of this
hand = sorted(cards, key=lambda card: card.suit) # sort
some iterable of cards by suit
# do this
hand = sorted(cards, key=(card.suit from card)) # sort
some iterable of cards by suit
#
|<= you can stop reading here and still have a
good sense of what the code does
More generally, I think a superior syntax for lambda would
be:
(<expression> from <signature>)
The reasons I believe that's a superior syntax are:
a) In the vast majority of use cases for lambda expressions
the call signature can be easily inferred (like in a key
function), so moving it after the expression tends to be more
readable.
b) It doesn't use the esoteric name, 'lambda' which causes
its own readability issues.
c) It should be compatible with existing code:
try:
1/0
except Exception as e:
raise (ValueError() from e) # this
is already a syntax error so implementing the proposal
won't break working code
# of
this form. I'm not aware of any other uses of the 'from'
keyword that would create
#
ambiguities
I'm not sure if this should actually be implemented, but I
wanted to share the idea anyway and get some feedback. In my
opinion 'lambda' is one of the less elegant pieces of Python
syntax not because it's restricted to a single expression, but
because the name and syntax are both detrimental to
readability.