Home >Backend Development >Python Tutorial >What is `functools.partial` in Python?
Read that complete article on Global News One
functools.partial creates a new function by partially applying arguments to an existing function. This is helpful for simplifying function calls in scenarios where certain arguments are repetitive or fixed.
The functools.partial function in Python allows you to "freeze" some portion of a function's arguments or keywords, creating a new function with fewer parameters. It's especially useful when you want to fix certain parameters of a function while keeping others flexible.
from functools import partial
partial(func, *args, **kwargs)
The returned object is a new function where the fixed arguments are "frozen," and you only need to supply the remaining ones when calling the new function.
def power(base, exponent): return base ** exponent # Create a square function by fixing exponent = 2 square = partial(power, exponent=2) # Now, square() only needs the base print(square(5)) # Output: 25 print(square(10)) # Output: 100
Here, partial creates a new function square that always uses exponent=2.
Suppose you have a function with multiple arguments, and you often call it with some fixed values.
def greet(greeting, name): return f"{greeting}, {name}!" # Fix the greeting say_hello = partial(greet, greeting="Hello") say_goodbye = partial(greet, greeting="Goodbye") print(say_hello("Alice")) # Output: Hello, Alice! print(say_goodbye("Alice")) # Output: Goodbye, Alice!
You can use partial to adapt a function for operations like map.
def multiply(x, y): return x * y # Fix y = 10 multiply_by_10 = partial(multiply, y=10) # Use in a map numbers = [1, 2, 3, 4] result = map(multiply_by_10, numbers) print(list(result)) # Output: [10, 20, 30, 40]
Partial works seamlessly with functions that already have default arguments.
def add(a, b=10): return a + b # Fix b to 20 add_with_20 = partial(add, b=20) print(add_with_20(5)) # Output: 25
You can use partial with libraries like Pandas to simplify repetitive operations.
from functools import partial
partial(func, *args, **kwargs)
def power(base, exponent): return base ** exponent # Create a square function by fixing exponent = 2 square = partial(power, exponent=2) # Now, square() only needs the base print(square(5)) # Output: 25 print(square(10)) # Output: 100
def greet(greeting, name): return f"{greeting}, {name}!" # Fix the greeting say_hello = partial(greet, greeting="Hello") say_goodbye = partial(greet, greeting="Goodbye") print(say_hello("Alice")) # Output: Hello, Alice! print(say_goodbye("Alice")) # Output: Goodbye, Alice!
Using functools.partial can simplify and clean up your code, especially when dealing with repetitive function calls or higher-order functions. Let me know if you'd like more examples or advanced use cases!
The above is the detailed content of What is `functools.partial` in Python?. For more information, please follow other related articles on the PHP Chinese website!