Home>

Please tell me about higher-order functions in Python.

I couldn't imagine the order of processing the next higher-order function sample code.

def log_func (func):
  def inner (* args, ** keywds):
    print ('-----------------')
    print (f'Name: {func.__name__}')
    print (f'Args: {args}')
    print (f'Keywds: {keywds}')
    print ('-----------------')
    return func (* args, ** keywds)
  return inner
def hoge (x, y, m ='bar', n ='piyo'):
  print (f'hoge: {x}-{y}/{m}-{n}')
log_hoge = log_func (hoge)
log_hoge (15, 37, m ='hoge', n ='piyo')

So, I put print in various places as follows and tried to process it.

def log_func (func):
  print ("A")
  def inner (* args, ** keywds):
    print ("B")
    print ('-----------------')
    print (f'Name: {func.__name__}')
    print (f'Args: {args}')
    print (f'Keywds: {keywds}')
    print ('-----------------')
    return func (* args, ** keywds)
  print ("C")
  return inner
def hoge (x, y, m ='bar', n ='piyo'):
  print ("D")
  print (f'hoge: {x}-{y}/{m}-{n}')
print ("E")
log_hoge = log_func (hoge)
print ("F")
log_hoge (15, 37, m ='hoge', n ='piyo')

This output result is

E
A
C
F
B
-----------------
Name: hoge
Args: (15, 37)
Keywds: {'m':'hoge','n':'piyo'}
-----------------
D
hoge: 15-37/Hoge-Piyo

have become.

I have a question here.
For myself
E → A → C → B → D → F
I was expecting it to be, but it didn't seem to be the case.
In short, since the inner function is called with return immediately after C, I thought that after C, I would go to B inside the inner function.

Could you please tell me why you fly to point F instead of the inner function after C?

  • Answer # 1

    Understand that the definition of a function and the execution of a function are different.

    The next return inner of print ("C") does not execute the inner, it just returns the defined function inner. Try the following:

    >>>log_hoge = log_func (hoge)
    A
    C
    >>>print (log_hoge)
    <function log_func.<locals>.inner at 0x0000025B43F024C0>
    >>>print (log_hoge.__name__)
    inner


    So far, we've just received the defined function inner and assigned it to log_hoge, so inner hasn't been executed yet.

  • Answer # 2

    Immediately after C, the inner function is called with return, so I was wondering if C would go to B inside the inner function.

    return innerDoes not "execute" the inner function. It's just returning the definition.
    B is displayed when the inner function is "executed", that is, after F when the inner function as the variable log_hoge is executed.