What is partial function in Python? Syntax and example.
A partial function is a function created using an existing function.
If we have a function with a certain functionality and want to make a new function with similar functionality, we can do this by assigning specific values to some parameters of the existing function. This newly created function is then called a partial function.
Syntax:
from functools import partial
new_function = partial(original_function, fixed_arg1, fixed_arg2, ...)
Example for partial function:
Problem: Let's say we have an existing function that has the functionality to take two arguments and perform multiplication on them. Now, I want to create a new function that uses this existing function to perform squaring instead.
How would I go about doing this with a partial function?
Existing function:
def multiplication(a, b):
multi = a * b
print(multi)
multiplication(10, 4)
Output:
40
Now create a new function with the help of the existing function:
from functools import partial
def multiplication(a, b):
multi = a * b
print(multi)
squere = partial(multiplication, b=2) # partial function
squere(3)
Output:
40
20 unique and in-depth interview questions on partial functions in Python
Question 1. What is the primary use of a partial function in Python?
Answer: A partial function allows you to create a new function from an existing one by pre-filling some of its arguments, making the new function easier to use when certain arguments don’t need to be changed.
Example:
from functools import partial
def multiply(x, y):
return x * y
double = partial(multiply, y=2)
print(double(5))
Output:
10
Question 2. How do you create a partial function with both positional and keyword arguments?
Answer: You can mix positional and keyword arguments in partial(), setting both types in the new function.
Example:
from functools import partial
def greet(greeting, name):
return f"{greeting}, {name}!"
greet_hello = partial(greet, "Hello", name="Alice")
print(greet_hello())
Output:
Hello, Alice!
Question 3. Can you create a partial function with all arguments pre-filled?
Answer: Yes, by pre-filling all arguments in partial(), the result is a function that requires no further arguments.
Example:
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, 2, 2)
print(square())
Output:
4
Question 4. How would you use a partial function to transform a function with optional parameters into one with fixed values?
Answer: You can pre-fill optional parameters in partial() to fix values for those parameters.
Example:
from functools import partial
def volume(length, width, height=10):
return length * width * height
fixed_height_volume = partial(volume, height=5)
print(fixed_height_volume(2, 3))
Output:
30
Question 5. Question: How can partial functions improve code readability in repeated operations?
Answer: By reducing the number of arguments required for frequently used functions, partial functions make the code cleaner and more concise.
Question 6. How can you use partial functions to convert between units, such as miles to kilometers?
Answer: A partial function can be used to simplify conversions by pre-filling a multiplication factor.
Example:
from functools import partial
def convert(value, factor):
return value * factor
miles_to_km = partial(convert, factor=1.60934)
print(miles_to_km(10))
Output:
16.0934
Question 7. Can you use partial functions in a lambda expression? Give an example.
Answer: Yes, partial functions can be combined with lambda expressions.
Example:
from functools import partial
def add(x, y):
return x + y
add_5 = lambda y: partial(add, 5)(y)
print(add_5(3))
Output:
8
Question 8. How does functools.partial handle default values set in the original function?
Answer: functools.partial allows you to override the default values of arguments set in the original function.
Question 9. How can partial functions help when using callback functions?
Answer: Partial functions allow you to pre-fill arguments for callbacks, making them more customizable for different situations.
Question 10. How would you use partial functions to filter a list of dictionaries by a specific key?
Answer: You can use partial functions to pre-fill the key to filter on.
Example:
from functools import partial
def filter_by_key(data, key, value):
return [item for item in data if item[key] == value]
data = [{'name': 'Alice'}, {'name': 'Bob'}, {'name': 'Alice'}]
filter_alice = partial(filter_by_key, key='name', value='Alice')
print(filter_alice(data))
Output:
[{'name': 'Alice'}, {'name': 'Alice'}]
Question 11. What happens if you try to pass new values for pre-filled arguments in a partial function?
Answer: The pre-filled values take precedence, and new values for those arguments are ignored.
Question 12. How would you use a partial function to cache database queries?
Answer: You can pre-fill parameters related to database access, like table name or database credentials, making it easy to cache results based on pre-set configurations.
Question 13. How can you use functools.partialmethod with partial functions in a class?
Answer: partialmethod allows you to create partial functions within classes by pre-filling methods.
Example:
from functools import partialmethod
class Calculator:
def power(self, base, exponent):
return base ** exponent
square = partialmethod(power, exponent=2)
calc = Calculator()
print(calc.square(3))
Output:
9
Question 14. How would you use partial functions to schedule tasks in Python?
Answer: You can use partial to pre-fill arguments for tasks, making scheduling more flexible.
Question 15. Can you use partial functions with decorators? How?
Answer: Yes, partial functions can simplify decorator usage by pre-filling some decorator arguments.
Question 16. How does functools.partial affect the __name__ and __doc__ attributes of the new function?
Answer: Partial functions don't inherit the __name__ or __doc__ of the original function but can be accessed via func.__name__ and func.__doc__.
Question 17. How would you apply a partial function to read files with different encodings?
Answer: Use partial to set the encoding argument, creating functions tailored for each encoding type.
Question 18. How can partial functions help in testing by pre-filling mock arguments?
Answer: You can pre-fill values commonly used in tests to create more controlled testing environments.
Question 19. Can you create a partial function that accepts a variable number of arguments (using *args and **kwargs)?
Answer: Yes, partial functions can handle *args and **kwargs, making them adaptable to dynamic arguments.
Question 12. How does a partial function affect the performance of function calls?
Answer: Partial functions add minimal overhead, though they may slightly impact performance due to the added layer of argument handling.
Tags:
Leave a comment
You must be logged in to post a comment.