Programming with Python · free preview
Functions at the Next Level
Write functions that accept flexible arguments, avoid the mutable-default trap, and wrap other functions with closures and decorators.
1. Overview
Overview
2. Flexible Arguments
Flexible Arguments
3. The Mutable Default Trap
The Mutable Default Trap
4. Lambda and Sorting Keys
Lambda and Sorting Keys
5. Closures
Closures
6. Decorators
Decorators
7. Flexible Logger
Flexible Logger
8. A Counting Decorator
A Counting Decorator
9. Recursion: functions that call themselves
Recursion: functions that call themselves
10. Trace decorator state
A run_logger decorator increments a counter before each call. For print(square(4)) then print(square(5)), give the four output lines in order, comma-separated.
11. Tracing the mutable-default fix
Run the fixed append_to three times: twice with the default omitted and once with an explicit shared list. Predict the list printed at each step and whether the explicit caller list changes.
Example. Tracing the mutable-default fix
Problem. Run the fixed append_to three times: twice with the default omitted and once with an explicit shared list. Predict the list printed at each step and whether the explicit caller list changes.
Correct solution.
def append_to(value, box=None):
if box is None:
box = []
box.append(value)
return box
first = append_to(1)
second = append_to(2)
shared = [36.6]
third = append_to(37.0, shared)
print(first)
print(second)
print(third)
print(shared)关键提醒。
Input is the sequence of calls append_to(1), append_to(2), and append_to(37.0, shared) where shared starts as [36.6].
Trace:
append_to(1)reachesif box is None, soboxbecomes a fresh[]; appending gives[1].append_to(2)repeats that creation. It does not see the first call's box, so it returns[2], not[1, 2].append_to(37.0, shared)receives the caller's list, appends into that same object, and returns it, sothirdandsharedboth print[36.6, 37.0].
Expected output:
Output
[1]
[2]
[36.6, 37.0]
[36.6, 37.0]12. Retrieval practice
Complete collect(kind, *values, **options) so it returns (kind, values, tuple(options.items())). What exact value does collect("vitals", 36.6, 37.0, unit="celsius", site="A") return?
def collect(kind, *values, **options):
return ____
value = collect("vitals", 36.6, 37.0, unit="celsius", site="A")13. Mastery check
Write a decorator run_logger that prints run N before each call and returns the wrapped function's result unchanged. Apply it to square(value) returning value * value, then print square(4) and square(5). Give the decorator, the decorated calls, and the exact console output.
def run_logger(func):
# complete the decorator
@run_logger
def square(value):
return value * value
print(square(4))
print(square(5))Practice this interactively
Free account · instant grading · spaced review that schedules itself.
Start this course for free