Code Explanation:
Line 1: def pack(f):
Defines a function pack that takes another function f as an argument.
This is a higher-order function (a function that works with other functions).
Line 2–3: Inner Function wrap(x) and Return
def wrap(x): return (f(x), x)
return wrap
wrap(x) is a nested function that:
Calls f(x) and returns a tuple: (f(x), x)
pack(f) finally returns this wrap function.
Purpose: It wraps any function so that calling it returns both the result and the original input.
Line 4: Using Decorator @pack
@pack
def square(x): return x ** 2
This is equivalent to:
def square(x): return x ** 2
square = pack(square)
So now square is actually the wrap function returned by pack.
Meaning:
square(3) → (square(3), 3) → ((3**2), 3) → (9, 3)
Line 5: Function Call and Indexing
print(square(3)[1])
square(3) now returns (9, 3)
square(3)[1] accesses the second element of the tuple, which is 3.
print(...) prints that value to the screen.
Final Output:
3
.png)

0 Comments:
Post a Comment