`functools.partial`: Freezing Function Arguments
`functools.partial(func, *args, **kwargs)` freezes certain arguments of a function, returning a new callable with a simpler signature 🧊.
from functools import partial
def multiply(x, y):
return x * y
# Freeze x=2 into a dedicated specialized function:
double = partial(multiply, 2)
print(double(5)) # 10 âš¡
print(double(20)) # 40 🚀
# 30. `functools.partial`: Freezing Function Arguments `functools.partial(func, *args, **kwargs)` freezes certain arguments of a function, returning a new callable with a simpler signature 🧊: ```python from functools import partial def multiply(x, y): return x * y # Freeze x=2 into a dedicated specialized function: double = partial(multiply, 2) print(double(5)) # 10 ⚡ print(double(20)) # 40 🚀 ``` Instead of wrapping functions in clumsy lambda boilerplate like `lambda y: multiply(2, y)`, `partial` creates an optimized, inspectable callable that preserves original function metadata. 🧠--- ### Question What does `functools.partial(pow, 2)` do? 🧊 - [ ] a. Creates a new function where the first argument (base 2) is already pre-filled - [ ] b. Immediately raises an unhandled TypeError - [ ] c. Executes pow(2, 2) and deletes the function 💥 - [ ] d. Compiles the function into machine assembly 🤖 --- ### Challenge Use `partial` to create a function `greet_user` from `def greet(greeting, name): return f"{greeting}, {name}!"` freezing `greeting="Hello"`. Call `greet_user("Dev")` and print the result. 🎯 <details> <summary>Solution</summary> ```python from functools import partial def greet(greeting, name): return f"{greeting}, {name}!" greet_user = partial(greet, "Hello") print(greet_user("Dev")) ``` </details>