views:

6265

answers:

19

I'm just beginning Python and ran head first into Lambda- which took me a while to figure out. Is lambda one of those 'interesting' language items that in real life should be forgotten? I'm sure there are some edge cases where it might be needed, but given the obscurity of it, the potential of it being redefined in future releases (my assumption based on the various definitions of it) and the reduced coding clarity - should it be avoided? This reminds me of overflowing (buffer overflow) of C types - pointing to the top variable and overloading to set the other field values...sort of a techie showmanship but maintenance coder nightmare..

+4  A: 

I can't speak to python's particular implementation of lambda, but in general lambda functions are really handy. They're a core technique (maybe even THE technique) of functional programming, and they're also very useuful in object-oriented programs. For certain types of problems, they're the best solution, so certainly shouldn't be forgotten!

I suggest you read up on closures and the map function (that links to python docs, but it exists in nearly every language that supports functional constructs) to see why it's useful.

rmeador
That stuff can be done without lambdas. It's just a big hassle.
Brian
+5  A: 

Pretty much anything you can do with lambda you can do better with either named functions or list and generator expressions.

Consequently, for the most part you should just one of those in basically any situation (except maybe for scratch code written in the interactive interpreter).

Aaron Maenpaa
"for the most part you should just one of those in basically any situation" Period. Typing lambda's in the interpreter isn't even that helpful.
S.Lott
lambda is one of those rare features that is so hard to overuse. anywhere you can use it, it will improve readability and maintainability. the only requisite is to really understand closures. if you don't understand them, you'll be left to believe such nonsense as this answer.
Javier
@Javier I agree with you if you are talking about "lambda" the concept; however, if we're talking about "lambda" the python keyword then: 1) named functions are faster and can do more (statements+expressions) almost anywhere you would use lambdas (map+filter) you can just generator expressions or list comprehensions which are more performant and concise. I'm not saying that first class functions aren't cool, just that the "lambda" keyword in python isn't as good as just using a named function, that's all.
Aaron Maenpaa
lambda has been indispensable to me for use with functions that take callback arguments like the key= argument to sort() and sorted()
Rick Copeland
@Rick I don't doubt that, but the reality is if when you see "lambda" and you think "zohmygod lambda" and start writing scheme code in python you will surly be disappointing by the limitations of python's lambda expression. On the other hand, if you start out thinking to yourself "Will a list comprehension work? No. Will what I need benifit from being a named function? No. Okay fine: sorted(xs, key = lambda x: x.name, x.height)", you will probably end up using lambda the right number of times.
Aaron Maenpaa
@Aaron - Agreed, lambda to me is a tool of nearly last resort. But it's really handy for those last resorts. I would *never* use lambda with map() or filter(), in particular. (The only reason to use map or filter, IMO, rather than a comprehension is that it can be faster if you're using a function implemented in C, and that advantage goes away if you use lambda.)
Rick Copeland
One of my few real uses of map is in this idiom... " ".join(map(str,iterable)) and friends, where the thing to apply over the iterable is a "type" function.
Gregg Lind
+13  A: 

I doubt lambda will go away. See Guido's post about finally giving up trying to remove it. http://mail.python.org/pipermail/python-dev/2006-February/060415.html

You might check out this post for more of a history about the deal behind Python's functional features: http://python-history.blogspot.com/2009/04/origins-of-pythons-functional-features.html

Curiously, the map, filter, and reduce functions that originally motivated the introduction of lambda and other functional features have to a large extent been superseded by list comprehensions and generator expressions. In fact, the reduce function was removed from list of builtin functions in Python 3.0. (However, it's not necessary to send in complaints about the removal of lambda, map or filter: they are staying. :-)

My own two cents: Rarely is lambda worth it as far as clarity goes. Generally there is a more clear solution that doesn't include lambda.

rhettg
note that reduce is still importable in Python 3.0. If You REALLY want it, You can still have it.
Reef
A: 

Lambdas are deeply liked to functional programming style in general. The idea that you can solve problems by applying a function to a data, and merging the results, is what google uses to implement most of its algorithms. Programs written in functional rpogramming style, are easily parrallelized and hence are becoming more and more important with modern multiu core machiines. So in short, NO you should not forget them.

Yogi
+1  A: 

First congrats that managed to figure out lambda. In my opinion this is really powerful construct to act with. The trend these days towards functional programming languages is surely an indicator that it neither should be avoided nor it will be redefined in the near future.

You just have to think a little bit different. I'm sure soon you will love it. But be careful if you deal only with python. Because the lambda is not a real closure, it is "broken" somehow

pythons lambda is broken

Norbert Hartl
Python's lambda is not broken. There are two ways to handle locals in lambdas. Both have advantages and disadvantages. I think the approach Python (and C#) took is probably counterintuitive to those more accustomed to purely functional languages, since with a purely functional language I don't think that approach even makes sense.
Brian
It is indeed counterintuitive. I'm not a python programmer but in squeak smalltalk it is the same and I stumple upon this regularly. So even I would consider it "broken" :)
Norbert Hartl
+4  A: 

I've been using Python for a few years and I've never run in to a case where I've needed lambda. Really, as the tutorial states, it's just for syntactic sugar.

Matt Schmidt
+20  A: 

A lambda is part of a very important abstraction mechanism which deals with higher order functions. To get proper understanding of its value, please watch high quality lessons from Abelson and Sussman, and read the book SICP

These are relevant issues in modern software business, and becoming ever more popular.

egaga
+1 for SICP. Everyone should read that book. If it doesn't kill you it WILL make you stronger.
Trey
+1, this was exactly the answer that I was going to write when I first clicked on this question. :)
Emil H
Lambda expressions are becoming popular in other languages (like C#) as well. They're not going anywhere. Reading up on closures would be a useful exercise to understand Lambdas. Closures make a lot of coding magic possible in frameworks like jQuery.
Dan Esparza
+41  A: 

Are you talking about lambda functions? Like

f = lambda x: x**2 + 2*x - 5

Those things are actually quite useful. Python supports a style of programming called functional programming where you can pass functions to other functions to do stuff. Example:

mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])

sets mult3 to [3, 6, 9], those elements of the original list that are multiples of 3. This is shorter (and, one could argue, clearer) than

def filterfunc(x):
    return x % 3 == 0
mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9])

Of course, in this particular case, you could do the same thing as a list comprehension:

mult3 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0]

(or even as range(3,10,3)) but there are other cases, like constructing functions as return values from other functions, where you can't use a list comprehension and a lambda function may be the shortest way to write something out. Like

def transform(n):
    return lambda x: x + n
f = transform(3)
f(4) # is 7

I use lambda functions on a regular basis. It took a while to get used to them but once I did I'm glad Python has them ;-)

David Zaslavsky
lambda is one of the requisites for a readable functional language. it's a pity that Python's syntax makes them so limited. still, it's miles ahead of any language without it.
Javier
@Jaiver: What limitations of Python lambda syntax did you encounter?
Xavier Ho
@David: you mind changing l to something? it looks like 1
Tshepang
@Tshepang: sure, good idea.
David Zaslavsky
@Xavier: I believe Javier is referring to verbosity of the `lambda` keyboard, and possibly the fact that you can only use expressions in Python lambdas. Contrast C#: `x => ...`, or Haskell: `\x -> ...` with Python `lambda x: ...`.
Porges
@Porges: The verbosity is a minor problem. The fact thta you can only use a SINGLE expression (and no statements) is a far more serious problem.
JUST MY correct OPINION
@David Zaslavsky: Not sure why you added "(or even as `range(3,10,3)`)"; it distracts from a perfectly good answer.
Nikhil Chelliah
@Nikhil: just making the point that one would never actually use that particular list comprehension in practice.
David Zaslavsky
@David Zaslavsky: Agreed! I was just saying that it's not your answer's job to teach the `range` function. If you want to show an *appropriate* use of `filter` or list comprehensions, then perhaps the original list ought to be something like `[1,2,3,8,5,7,9,'camels',-23]`?
Nikhil Chelliah
@Nikhil: well, a numeric list was just the easiest thing to type. Anyway, I see your point but I just don't think the brief mention of `range` is too distracting.
David Zaslavsky
A: 

Lambda is a procedure constructor. You can synthesize programs at run-time, although Python's lambda is not very powerful. Note that few people understand that kind of programming.

Nick D
+1  A: 

I'm just beginning Python and ran head first into Lambda- which took me a while to figure out.

Note that this isn't a condemnation of anything. Everybody has a different set of things that don't come easily.

Is lambda one of those 'interesting' language items that in real life should be forgotten?

No.

I'm sure there are some edge cases where it might be needed, but given the obscurity of it,

It's not obscure. The past 2 teams I've worked on, everybody used this feature all the time.

the potential of it being redefined in future releases (my assumption based on the various definitions of it)

I've seen no serious proposals to redefine it in Python, beyond fixing the closure semantics a few years ago.

and the reduced coding clarity - should it be avoided?

It's not less clear, if you're using it right. On the contrary, having more language constructs available increases clarity.

This reminds me of overflowing (buffer overflow) of C types - pointing to the top variable and overloading to set the other field values...sort of a techie showmanship but maintenance coder nightmare..

Lambda is like buffer overflow? Wow. I can't imagine how you're using lambda if you think it's a "maintenance nightmare".

Ken
-1 for making me (and others) read the whole question again. Note that others managed to answer without doing it.
Reef
+1  A: 

I use it quite often, mainly as a null object or to partially bind parameters to a function.

Here are examples:

to implement null object pattern:

{
 DATA_PACKET: self.handle_data_packets
 NET_PACKET: self.handle_hardware_packets
}.get(packet_type, lambda x : None)(payload)

for parameter binding:

let say that I have the following API

def dump_hex(file, var)
    # some code
 pass

class X(object):
    #...
 def packet_received(data):
  # some kind of preprocessing
  self.callback(data)
    #...

Then, when I wan't to quickly dump the recieved data to a file I do that:

dump_file = file('hex_dump.txt','w')
X.callback = lambda (x): dump_hex(dump_file, x)
...
dump_file.close()
Piotr Czapla
+8  A: 

The two-line summary:

  1. Closures: Very useful. Learn them, use them, love them.
  2. Python's lambda keyword: unnecessary, occasionally useful. If you find yourself doing anything remotely complex with it, put it away and define a real function.
John Fouhy
A: 

I started reading David Mertz's book today 'Text Processing in Python.' While he has a fairly terse description of Lambda's the examples in the first chapter combined with the explanation in Appendix A made them jump off the page for me (finally) and all of a sudden I understood their value. That is not to say his explanation will work for you and I am still at the discovery stage so I will not attempt to add to these responses other than the following: I am new to Python I am new to OOP Lambdas were a struggle for me Now that I read Mertz, I think I get them and I see them as very useful as I think they allow a cleaner approach to programming.

He reproduces the Zen of Python, one line of which is Simple is better than complex. As a non-OOP programmer reading code with lambdas (and until last week list comprehensions) I have thought-This is simple?. I finally realized today that actually these features make the code much more readable, and understandable than the alternative-which is invariably a loop of some sort. I also realized that like financial statements-Python was not designed for the novice user, rather it is designed for the user that wants to get educated. I can't believe how powerful this language is. When it dawned on me (finally) the purpose and value of lambdas I wanted to rip up about 30 programs and start over putting in lambdas where appropriate.

PyNEwbie
A: 
dbr
A: 

Hmm, dbr's comment is very puzzling. I tried his example:

>>> fs = [(lambda n: i+n) for i in range(10)]

>>> [fs[i](3) for i in range(10)]
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

>>> for i in range(10):
...     print fs[i](3)
... 
3
4
5
6
7
8
9
10
11
12

So far, so good. This makes sense to me. But what the heck is going on here?

>>> fs[0](3)
12
>>> fs[1](3)
12
>>> fs[2](3)
12
>>> fs[3](3)
12

I'm completely stumped. Am I missing something obvious here?

Ah, I just found the answer to my own question:

http://stackoverflow.com/questions/1107210/python-lambda-problems

Greg
A: 

lambda is just a fancy way of saying function. Other than its name, there is nothing obscure, intimidating or cryptic about it. When you read the following line, replace lambda by function in your mind:

>>> f = lambda x: x + 1
>>> f(3)
4

It just defines a function of x. Some other languages, like R, say it explicitly:

> f = function(x) { x + 1 }
> f(3)
4

You see? It's one of the most natural things to do in programming.

A: 

One of the nice things about lambda that's in my opinion understated is that it's way of deferring an evaluation for simple forms till the value is needed. Let me explain.

Many library routines are implemented so that they allow certain parameters to be callables (of whom lambda is one). The idea is that the actual value will be computed only at the time when it's going to be used (rather that when it's called). An (contrived) example might help to illustrate the point. Suppose you have a routine which which was going to do log a given timestamp. You want the routine to use the current time minus 30 minutes. You'd call it like so

log_timestamp(datetime.datetime.now() - datetime.timedelta(minutes = 30))

Now suppose the actual function is going to be called only when a certain event occurs and you want the timestamp to be computed only at that time. You can do this like so

log_timestamp(lambda : datetime.datetime.now() - datetime.timedelta(minutes = 30))

Assuming the log_timestamp can handle callables like this, it will evaluate this when it needs it and you'll get the timestamp at that time.

There are of course alternate ways to do this (using the operator module for example) but I hope I've conveyed the point.

Update: Here is a slightly more concrete real world example.

Noufal Ibrahim
A: 

I find lambda useful for a list of functions that do the same, but for different circumstances. Like the mozilla plural rules.

plural_rules = [
    lambda n: 'all',
    lambda n: 'singular' if n == 1 else 'plural',
    lambda n: 'singular' if 0 <= n <= 1 else 'plural',
    ...
]
# Call plural rule #1 with argument 4 to find out which sentence form to use.
plural_rule[1](4) # returns 'plural'

If you'd have to define a function for all of those you'd go mad by the end of it. Also it wouldn't be nice with function names like plural_rule_1, plural_rule_2, etc. And you'd need to eval() it when you're depending on a variable function id.

Tor Valamo
A: 

As stated above, the lambda operator in Python defines an anonymous function, and in Python functions are closures. It is important not to confuse the concept of closures with the operator lambda, which is merely syntactic methadone for them.

When I started in Python a few years ago, I used lambdas a lot, thinking they were cool, along with list comprehensions. However, I wrote and have to maintain a big website written in Python, with on the order of several thousand function points. I've learnt from experience that lambdas might be OK to prototype things with, but offer nothing over inline functions (named closures) except for saving a few key-stokes, or sometimes not.

Basically this boils down to several points:

  • it is easier to read software that is explicitly written using meaningful names. Anonymous closures by definition cannot have a meaningful name, as they have no name. This brevity seems, for some reason, to also infect lambda parameters, hence we often see examples like lambda x: x+1
  • it is easier to reuse named closures, as they can be referred to by name more than once, when there is a name to refer to them by.
  • it is easier to debug code that is using named closures instead of lambdas, because the name will appear in tracebacks, and around the error.

That's enough reason to round them up and convert them to named closures. However, I hold two other grudges against anonymous closures.

The first grudge is simply that they are just another unnecessary keyword cluttering up the language.

The second grudge is deeper and on the paradigm level, i.e. I do not like that they promote a functional-programming style, because that style is less flexible than the message passing, object oriented or procedural styles, because the lambda calculus is not Turing-complete (luckily in Python, we can still break out of that restriction even inside a lambda). The reasons I feel lambdas promote this style are:

  • There is an implicit return, i.e. they seem like they 'should' be functions.

  • They are an alternative state-hiding mechanism to another, more explicit, more readable, more reusable and more general mechanism: methods.

I try hard to write lambda-free Python, and remove lambdas on sight. I think Python would be a slightly better language without lambdas, but that's just my opinion.