6 ms·
Can you elaborate on this? What is wrong with Python's `lambda`?
by 0x2c8 6y ago
Can you elaborate on this? What is wrong with Python's `lambda`?
- kissgyorgy 6y agoIt can only have one line for example.
- Iwan-Zotow 6y agono, not correct
- pansa2 6y agoPython’s `lambda` can only contain a single expression. There’s no good way to add support for full anonymous functions to Python’s grammar. One of the rules that makes significant-whitespace work elegantly is that statements can contain expressions, but never vice-versa.
- omaranto 6y agoPlenty of languages with significant-whitespace have multiline anonymous functions, like Haskell, Standard ML, Ocaml, etc. Maybe it's no possible in Python for a student reason, but the reason is not that the syntax is bad on indentation.
- pansa2 6y agoThe syntaxes of those languages are fundamentally different from Python’s. They don’t have an “expressions may not contain statements” rule - they don’t even have statements.
- omaranto 6y agoIt sounds like you agree with me: the reason Python does not have multiline lambdas is not that it has significant-whitespace, but other decisions including the “expressions may not contain statements” rule.
- c-cube 6y agoNitpick : neither ocaml nor SML have significant whitespace.
- omaranto 6y agoYou're right! It's been too long since I used them. I think I was probably remembering F#'s light syntax.
- ausjke 6y agosince lambda is for simple and short anonymous functions most of the time why do I need type the whole word each time? can they also do what javascript does(or similar): x => x * 2 instead of lambda x : x * 2
- rustyminnow 6y agoLike others have said: - Can only have one line - Can only use expressions, not statements. E.g. `print`s, loops, conditionals are out. - Overall just kinda clunky Here's an SO post about lambdas where the answer is "Use def instead." https://stackoverflow.com/questions/14843777/how-to-write-python-lambda-with-multiple-lines https://stackoverflow.com/questions/14843777/how-to-write-py...
- bobbylarrybobby 6y agoThe lambda calculus is Turing complete, so in theory, Python’s lambdas should suffice...
- rustyminnow 6y agoI mean... You're right. They suffice. They're just less friendly (i.e. useful) than lambdas in other languages.
- zelphirkalt 6y agoWhich of course says nothing about usability and readability.
- jolux 6y agoTuring completeness is completely unrelated to whether or not anonymous functions are easy to use in Python.
- heavyset_go 6y agoprint() is a function now and you can use it with lambdas.
- pmiller2 6y agoEven in Python 2, you can do something like this: println = lambda s: sys.stdout.write(s + '\n') Not that it really makes things much better, but, at least it shows you can do it.
- 6y ago
- VWWHFSfQ 6y agoThe use of lambda is becoming somewhat of a smell in Python in general. PSF's own black code formatter will complain about using it and pretty much always says to just use a def instead