CaitlinG
CaitlinG

Reputation: 2015

Higher order functions in Python

My apologies for what some may regard as a fundamental question. 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 a reference to it is returned (forming a closure I assume?), but is the inner function executed or simply 'read' and not called until the programmer writes code like the following:

f = greet('Caroline')
f()

Upvotes: 5

Views: 122

Answers (1)

Kasravnd
Kasravnd

Reputation: 107297

Since every thing in python is about runtime (except compile time tasks like peephole optimizer and etc.), python doesn't call your function unless you call it.

You can see this behavior by using dis function from dis module, which returns the relative bytecode of your function :

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

As you can see in part 6 python just load the function as a code object in a CONST value.

Upvotes: 7

Related Questions