user3378649
user3378649

Reputation: 5354

Lambda function as class member

I am truing to write an idiomatic python here.

What is the best to write Lambda function as class member. and How can we comment it.

class foo:
    def run(self,x):
       """ I don't know what I am doing
       """
        return x*3


class foo:
    run= lambda x: x*3

Is there anyone to clarify this, from the lens of idiomatic python.

Upvotes: 0

Views: 3432

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 114038

as mentioned in the comments it is in general not suported (in addition to being a poor use of a lambda)... however by convention you would comment them the same as any other class member

 #: returns the square
 fred = lambda x:x*x

or

 fred = lambda x:x*x   #: returns the square

or even(although less aesthetically pleasing)

 fred = lambda x:x*x
 ''' returns the square '''

http://epydoc.sourceforge.net/manual-docstring.html#variable-docstrings

this method of documentation is pretty readable and is also supported by most auto-documentation tools

Upvotes: 2

steveha
steveha

Reputation: 76735

It's not illegal to use a lambda like that, but it's silly.

The point of lambda is to conveniently make a very lightweight function object, one whose use is so ephemeral that it's not even worth the bother of giving it a name. A classic example is simple callback functions for a GUI Framework:

shutdown_button_callbacks = {
    "on_mouse_click" : lambda: gui_shutdown("now"),
    "on_mouse_right_click": lambda: show_context_menu("shutdown_menu")
}

Since the callbacks here are really trivial, and they are just being poked into a dict for use by a GUI framework, it's convenient to just put them right there in the dict declaration.

If as you need to bind the function object to a name, you should just use a normal def statement. This not only binds the name, but also sets the .__name__ attribute on the function object, and it's the idiomatic way to do it in Python.

Python has a very limited lambda and the word from Guido van Rossum is that this will never change. So as soon as you need anything other than a single expression, you can't use a lambda anyway.

Both the def statement and lambda make function objects; the only difference is that def binds a name. You can still get a reference to the function object and store it, pass it around, etc. There is nothing "better" or special about a lambda function object.

P.S. Another classic use of lambda would be for a simple code snippet for a map() call:

map(lambda x: x**2, range(9))  # returns squares of numbers 0 through 8 inclusive

But common practice in Python would be to use a list comprehension, and you can just put in the code snippet without making a function out of it:

[x**2 for x in range(9)]

Upvotes: 4

Related Questions