Luke
Luke

Reputation: 1377

How to return closure in most straightforward way?

Let's say I want to have a function which produces functions (closures) which multiply their argument by the argument of the factory function.

Example in JavaScript:

function get_mult_by(m) {
    return function(x) {
        return m * x;
    }
}

In Python I can return lambda:

def get_mult_by(m):
    return lambda x: m * x

But if I want to return a normal function things get more complicated and less straightforward (starting with the necessity of naming the function):

def get_mult_by(m):
    def mult(x):
        # do something else
        return m * x
    return mult

What are the best practises in that matter?

Upvotes: 0

Views: 42

Answers (2)

yiliangt5
yiliangt5

Reputation: 1

They are same. To you question, I think using lambda is more pythonic. Actually if you do not import additional package, you cannot even distinguish them using type function:

In [4]: type(lambda x: 1)
Out[4]: function

In [5]: def f():
   ...:     pass
   ...:

In [6]: type(f)
Out[6]: function

If you think the complicated way is better, simply go with that and good for you.

Upvotes: 0

Tom Karzes
Tom Karzes

Reputation: 24052

I don't think it makes much difference. If the function is a simple expression, I'd probably return a lambda as in your first example, but using a named function should not be a problem. The JavaScript equivalent to the named function case would be:

function get_mult_by(m) {
    var mult;
    mult = function(x) {
        return m * x;
    }
    return mult;
}

In other words, just think of it as a local that you use to create the return value.

Upvotes: 1

Related Questions