3.8. FuncProg Higher-Order

3.8.1. Rationale

  • Function can take other function as arguments

  • Function can return function

3.8.2. Example

>>> def lower():
...     ...
>>>
>>>
>>> def higher():
...     return lower

3.8.3. Calling

>>> def lower():
...     return 'My name... José Jiménez'
>>>
>>> def higher():
...     return lower
>>>
>>>
>>> a = higher
>>> b = higher()
>>>
>>> a  
<function higher at 0x...>
>>>
>>> a()  
<function lower at 0x...>
>>>
>>> a()()
'My name... José Jiménez'
>>>
>>> b  
<function lower at 0x...>
>>>
>>> b()
'My name... José Jiménez'

3.8.4. Use Case

>>> def http_request(url, on_success, on_error):
...     try:
...         result = ...
...     except Exception as error:
...         return on_error(error)
...     else:
...         return on_success(result)
>>>
>>>
>>> http_request(
...     url = 'https://python.astrotech.io',
...     on_success = lambda result: print(result),
...     on_error = lambda error: print(error))
Ellipsis