2

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?

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
pangpang
  • 8,581
  • 11
  • 60
  • 96
  • 1
    Possible duplicate of [Restrictons of Python compared to Ruby: lambda's](http://stackoverflow.com/questions/2654425/restrictons-of-python-compared-to-ruby-lambdas) – metatoaster Oct 27 '15 at 02:29
  • 1
    @metatoaster I think this is a part of answer. I wan t to know all the differences, not just restriction. – pangpang Oct 27 '15 at 02:44
  • 1
    Regardless, this question is also too broad, and stackoverflow is not a forum to discuss answers that are subjected to influences of opinions. – metatoaster Oct 27 '15 at 02:46

1 Answers1

1

Python lambdas versus functions

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 for functional programming

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.

Conclusion

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.

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331