Lesson 1 · Unit 08
Functions as values
Pass functions around, write tiny ones, wrap one in another
What you practise
- Passing a function to a function,
lambda, closures,*argsand**kwargs, a first decorator
Try a question from this lesson
Pick one
Look at line 5: the parameter func gets called, so whatever is passed in must be a function. What does this program show?
def shout(text):
return text.upper() + "!"
def twice(func, value):
return func(func(value))
print(twice(shout, "hi"))Hint
Work from the inside out: the inner call first, then the outer call on its result.
Correct answer
HI!!
Why
On line 7, shout has no brackets: it is not called, it is handed over. Inside, func is that function. The inner call gives "HI!", and the outer call shouts that again: "HI!!".
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Functions are values
A function's name without brackets is the function itself. Brackets call it.
So a function can be given a second name, stored in a list, or passed to another function, like any other value. You have done it before: sorted(words, key=len) passes len without calling it.
def shout(text):
return text.upper() + "!"
say = shout # no brackets
print(say("hi")) # HI!
tools = [shout, len]
print(tools[1]("hi")) # 2Concept
A function that makes functions
A function can be defined inside another function, and returned from it.
The inner function remembers the variables of the outer one, even after the outer one has finished. Here each function made by make_adder keeps its own n. This is called a closure.
def make_adder(n):
def add(x):
return x + n
return add
add5 = make_adder(5)
add100 = make_adder(100)
print(add5(1)) # 6
print(add100(1)) # 101Concept
A first decorator
A decorator takes a function and returns a new function that does something extra around it.
@loud above a def is short for greet = loud(greet). From then on, calling greet really calls the wrapper, and the wrapper calls the original.
def loud(func):
def wrapper(name):
return func(name).upper()
return wrapper
@loud
def greet(name):
return f"hello {name}"
print(greet("ada")) # HELLO ADA9 more exercises in the app
- 4× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.