def inside():
print("This is inside")
def outside(function):
function() outside(inside)
This is inside
April 5, 2023
Python functions can take functions as arguments and can return functions to their calling site.
This is inside
Inner functions can sometimes be referred to as callbacks as they are not invoked immediately. Forexample, passing a custom function to sorted()
:
fruits = ["apple", "tomato", "pear", "blueberry"]
def reverse_length(x):
return -len(x)
print(sorted(fruits, key=reverse_length))
['blueberry', 'tomato', 'apple', 'pear']
Functions can also return functions, which can be called without intermediate assignement:
This is inside
Lambda expressions can be useful and take the following form:
lambda <parameter_list (optional)>: <expression>
Lambda expressions have their own namespace, and can access but not modify global variables. For example:
reverse = lambda x: x[::-1]
callable(reverse)
print(reverse("Hello World!"))
print(reverse([1,2,3,4]))
print((lambda x1, x2: x1+x2)(2,2))
meaning_of_life = lambda: 42
print(meaning_of_life())
!dlroW olleH
[4, 3, 2, 1]
4
42
The return value of a lambda can only be a single expression, and not assignemnet or return statements, or other control constructs. It also does not allow implicit tuple unpacking. Tuples, lists and dictionaries can still be returned, but reqiore explicit parentheses:
Map can apply a function to each element of an iterable, and can return an iterator which can yield the results. Map takes the following form
map(<function>, <iterable>)
square = lambda x: x**2
numbers = [1,2,3,4,5,6,7]
iterable = map(square, numbers)
print(next(iterable))
print(next(iterable))
print(next(iterable))
print(list(iterable))
1
4
9
[16, 25, 36, 49]
Iterating over the iterable yeilds the items.
Map can also take the form map(<function>, <iterable$_1$>)
[^1] https://realpython.com/python-functional-programming/