Higher Order Functions in Python

I apologize for what some may consider as a fundamental issue. In the following simple code:

def greet(name):
    def say_hi():
        print('Preparing to greet...')
        print('Hi', name, '!')       
        print('Greeting given.')
    return say_hi

What is the sequence of events when greet is called with a formal parameter and the interpreter encounters the say_hi function. I see that the reference to it is returned (forming a closure, which I assume?), But the internal function is executed or simply "read" and is not called until the programmer writes the following code:

f = greet('Caroline')
f()
+4
source share
1 answer

python - ( , ..), python , .

, dis dis, - :

>>> def greet(name):
...     def say_hi():
...         print('Preparing to greet...')
...         print('Hi', name, '!')       
...         print('Greeting given.')
...     return say_hi
... 
>>> import dis
>>> 
>>> dis.dis(greet)
  2           0 LOAD_CLOSURE             0 (name)
              3 BUILD_TUPLE              1
              6 LOAD_CONST               1 (<code object say_hi at 0x7fdacc12c8b0, file "<stdin>", line 2>)
              9 MAKE_CLOSURE             0
             12 STORE_FAST               1 (say_hi)

  6          15 LOAD_FAST                1 (say_hi)
             18 RETURN_VALUE  

6, python CONST.

+6

Source: https://habr.com/ru/post/1621648/


All Articles