In Ruby, lambda can be used as anonymous function, and it is also an object.
But what about Python? I know Python lambda also can be used as anonymous function, but I want to know what are the other differences between them?
In Ruby, lambda can be used as anonymous function, and it is also an object.
But what about Python? I know Python lambda also can be used as anonymous function, but I want to know what are the other differences between them?
Python lambdas are fully functional function objects, they simply lack names and documentation (docstrings), and can only return expressions (no statements). So both named functions and lambdas have closures and can be passed around like objects.
Many Python programmers would prefer not to use Python lambdas because of their drawbacks and no plusses other than being able to provide them as arguments directly in function calls as opposed to creating a named function on a different line.
For Python, other than constraints in lamba creation, there is no difference between a function created by a lambda and a function created by a def
statement. Both are the same type of object:
>>> def foo(): return None
>>> bar = lambda: None
>>> import dis
>>> dis.dis(foo)
1 0 LOAD_CONST 0 (None)
3 RETURN_VALUE
>>> dis.dis(bar)
1 0 LOAD_CONST 0 (None)
3 RETURN_VALUE
Ruby lambdas are, as I understand it, the best practice way to do functional programming by passing around functions, as they provide closures - and they should be called with the .call
method. Ruby lambdas can contain complex/multiline expressions.
To compare, both are fully functional, provide lexical scoping (closures), are anonymous, and lack documentation.
To contrast, Python lambdas return a single expression, while Ruby lambdas can contain multiple lines. Python lambdas are expected to be called directly with possible arguments passed within parens, ()
, while Ruby lambda best practices is to use the .call
method.
Based on the tradeoffs and recognized best practices for each domain, one would expect those who program in Ruby to prefer lambdas, especially for functional programming, and those who use Python to prefer named functions.