Sreehari R
Sreehari R

Reputation: 979

How to apply a function to a value using the (var1)(var2) notation in python

I am solving a couple of problems in python In one of them, its asks me to write a function such that when examplefunction([1, 2, 3, 4])(10) returns something lets just say 10.

The trouble is, I've never seen notation using double ()() to call a function so far in python.

I've tried looking at multiple posts on stack overflow such as Python: Apply function to values in nested dictionary

But there is really no question like this.

Upvotes: 2

Views: 595

Answers (3)

Mike Scotty
Mike Scotty

Reputation: 10782

If you see (...)(...) it means that function calls are chained and the first function returns another function.

Example:

def fn1(val1):
    def fn2(val2):
        print("{} {}".format(val1, val2))
    return fn2

fn1("Hello")("World") # -> "Hello World"

# you can also write this as:
var1 = fn1("Hello")
var1("World")

Upvotes: 1

cosinepenguin
cosinepenguin

Reputation: 1575

Functions don't have multiple parameter brackets. Those are just referring to nested functions, or functions that incorporate other functions.

For example:

def func(a):
    def func2(b):
        return a + b
    return func2

Would be invoked like this:

func(1)(2)

(and would return 3 as an answer)

So it appears there are two parameter brackets, but really they are for two different functions!

Hope it helps!

Source

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1124110

object()() is just _result = object() and _result() chained. As long as the first call returns a callable object, the second call expression can proceed.

Have your examplefunction() call return another function. Functions are objects too, so you could just return an existing function:

def examplefunction():
    return secondfunction

def secondfunction():
    return 10

at which point examplefunction()() produces 10.

You can also have your examplefunction() call produce a new function object each time, by defining that function object as part of its body:

def examplefunction():
    def nestedfunction():
        return 10
    return nestedfunction

This gives the same result, but the added advantage that nestedfunction() has (read) access to all local names defined in examplefunction (these are called closures); this allows you to parameterise how nestedfunction() behaves:

def examplefunction(base):
    def nestedfunction():
        return base * 2
    return nestedfunction

examplefunction(5)()  # produces 10

I suspect that your assignment is trying to teach you these principles.

Upvotes: 8

Related Questions