JAbrams
JAbrams

Reputation: 325

Back to back parentheses in Python

I am watching a video and saw the following line of code:

encoded_frames = tf.keras.layers.TimeDistributed(cnn)(video)

Can someone please tell me what the "(cnn)(video)" part is doing? Is the (video) part an anonymous function being called?

Thanks

Upvotes: 0

Views: 419

Answers (2)

Seer.The
Seer.The

Reputation: 486

The class in question has __call__ method that allows to treat it's instances as functions.

To see exactly what happens in your specific case, you can have a look on official github of Keras (Layer class, TimeDistributed). Your class in question is ingerited like that: TimeDistributed <- Wrapper <- Layer. In Layer.__call__ we see that it's a wrapper around .call method, so here you go.

Upvotes: 0

shmee
shmee

Reputation: 5101

In this case, TimeDistributed appears to be callable (i.e. implements the __call__ method) and the second pair of parenthesis holds the arguments for the call to __call__

class Test:
def __init__(self, var):
    self.var = var

def one(self):
    print("running one")

def __call__(self, v):
    print("v: " + v)
    self.one()
    return "self.var: " + self.var

print(Test("1")("run"))

This yields

v: run
running one
self.var: 1    

Test("1") instantiates the Test object with the self.var value of "1", the ("run") imediately calls __call__ on the instance and passes "run" as a parameter to the __call__ method.

You can have similar constructs in other cases as well, e.g. if you access a callable object in a dict

def bla(v):
    return "in bla: " + v

d = {'func': bla}

print(d.get('func')('something')) # in bla: something

Upvotes: 1

Related Questions