What do double parentheses mean in a function call? e.g. func(stuff)(stuff)?

最后都变了- 提交于 2019-11-29 11:49:12

问题


Original title:

"Help me understand this weird Python idiom? sys.stdout = codecs.getwriter('utf-8')(sys.stdout)"

I use this idiom all the time to print a bunch of content to standard out in utf-8 in Python 2.*:

sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

But to be honest, I have no idea what the (sys.stdout) is doing. It sort of reminds me of a Javascript closure or something. But I don't know how to look up this idiom in the Python docs.

Can any of you fine folks explain what's going on here? Thanks!


回答1:


.getwriter returns a functioncallable object; you are merely calling it in the same line.

Example:

def returnFunction():
    def myFunction():
        print('hello!')
    return myFunction

Demo:

>>> returnFunction()()
hello!

You could have alternatively done:

>>> result = returnFunction()
>>> result()
hello!

Visualization:

evaluation step 0: returnSomeFunction()()
evaluation step 1: |<-somefunction>-->|()
evaluation step 2: |<----result-------->|



回答2:


codecs.getwriter('utf-8') returns a class with StreamWriter behaviour and whose objects can be initialized with a stream.

>>> codecs.getwriter('utf-8')
<class encodings.utf_8.StreamWriter at 0x1004b28f0>

Thus, you are doing something similar to:

sys.stdout = StreamWriter(sys.stdout)



回答3:


Calling the wrapper function with the double parentheses of python flexibility .

Example

1- funcWrapper

def funcwrapper(y):
    def abc(x):
        return x * y + 1
    return abc

result = funcwrapper(3)(5)
print(result)

2- funcWrapper

def xyz(z):
    return z + 1

def funcwrapper(y):
    def abc(x):
        return x * y + 1
    return abc

result = funcwrapper(3)(xyz(4))
print(result)


来源:https://stackoverflow.com/questions/6476825/what-do-double-parentheses-mean-in-a-function-call-e-g-funcstuffstuff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!