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

后端 未结 3 1062
悲哀的现实
悲哀的现实 2020-12-30 01:19

Original title:

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

3条回答
  •  轮回少年
    2020-12-30 01:27

    .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-------->|
    

提交回复
热议问题