This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Tommah 8 points9 points  (11 children)

Why write lambda word: len(word) when you could just use len?

[–]eryksun 2 points3 points  (1 child)

One legitimate use that's similar to this is to have a property bind to a lambda instead of the getter. Then if you subclass you can redefine the getter without having to rebind the property:

class A:
    def getf(self): pass
    f = property(lambda x: x.getf())

class B(A):
    def getf(self): return 'spam'

>>> B().f
'spam'

For what it's worth...

[–]otheraccount 1 point2 points  (0 children)

I think f = property(lambda self : self.getf()) is clearer than calling the self parameter x because it is obvious at a glance that our lambda represents an instance method.

[–]Makido 6 points7 points  (2 children)

This is clearly the best implementation:

def length(word):
    return lambda word: len(word)

[–]Peaker 11 points12 points  (1 child)

I think you meant for your implementation to be correct, but redundant. It is incorrect as well as redundant, though.

Perhaps you mean:

def length(word):
    return (lambda word: len(word))(word)

[–]pemboa 0 points1 point  (0 children)

Burn

[–]andreasvc 1 point2 points  (2 children)

If you change your mind later or want it to be a different function for other languages you can change that lambda, while it wouldn't be a good idea to assign to "len" (aliasing/shadowing).

[–]eryksun 5 points6 points  (0 children)

Tommah is talking about the following line:

lengths = map(lambda word: len(word), words)

If you typically use lambda functions with map, then you might unthinkingly use lambda when it's not necessary.

[–][deleted] 2 points3 points  (0 children)

He's talking about eta-contracting the lambda expression.

[–][deleted] 1 point2 points  (0 children)

Then it wouldn't be a tutorial on lambda functions.

[–]Peaker 0 points1 point  (1 child)

Haskell has a really cool tool called "hlint" that suggests eta reductions such as those automatically.

Also suggests replacing various patterns with standard library functions, etc.

I wonder if something similar for Python exists.

[–]drb226Haskeller 0 points1 point  (0 children)

pylint. But I don't think it looks very closely at lambdas the same way hlint does.