Python First Class Functions #
“First class” means a function can be treated like any other object or variable.
An example:
def square(x):
return x * x
f = square(5)
# print(square)
print(f)
# OR
f = square # assigns variable equal to function
^ Now f
is effectively the same as the function.
print(f(5)) # 25
Pass function as argument #
map()
is an example - takes function and array as arguments, returns a new array.
Writing a map functiion from scratch:
def my_map(func, arg_list):
result = []
for i in arg_list:
result.append(func(i))
return result
Colloquially, this takes a function and a list of arguments, runs the function on each argument, and appends each individual result to a results list.
squares = my_map(square, [1, 2, 3, 4, 5])
Note no parethesis - that would execute the function, which is not what we want when running a map.
With map, easy to swap out functions.
def cube(x):
return x * x * x
cubes = my_map(cube, [1, 2, 3, 4, 5])
Return function as results #
Return a function from another function.
This one can get tricky.
An example:
def logger(msg):
def log_message():
print('Log:', msg)
return log_message
log_hi = logger('Hi!')
log_hi()