SoFunction
Updated on 2024-12-19

Python3 implementation of reducing the number of arguments to a callable object

concern

A callable object that is used by other python code, possibly a callback function or a handler, causes an error when called because it has too many arguments.

prescription

If you need to reduce the number of arguments to a function, you can use (). The partial() function allows you to set a fixed value for one or more arguments, reducing the number of arguments that will be called next. Suppose a function has many arguments:

def func(a, b, c, d):
  print(a, b, c, d)

Use the partial() function to fix certain parameter values:

from functools import partial

s1 = partial(func, 1) # a = 1
print(s1(2, 3, 4))
(1, 2, 3, 4)

s2 = partial(func, d=100)  # d = 100
print(s2(1, 2, 3))
(1, 2, 3, 100)

s3 = partial(func, 1, 2, d=100) # a = 1, b = 2, d = 100
print(s3(3))
(1, 2, 3, 100)

You can see that the partial() function fixes certain arguments and returns a new callable object. This new callable takes the unassigned arguments, combines them with the previously assigned arguments, and passes all the arguments to the original function.

talk over

Suppose there is a list of points, points, representing (x, y) coordinate tuples. Now you need to use the point (4, 3) as a base and sort all the points in points based on the distance between the point and the base.

Define a function to calculate the distance between two points:

import math

points = [(1, 2), (3, 4), (5, 6), (7, 8)]
pt = (4, 3)

def distance(p1, p2):
  x1, y1 = p1
  x2, y2 = p2
  return (x2 - x1, y2 - y1)

The sort() sort method for lists can take a keyword argument to set up custom sorting logic, but it can only take a function with a single argument, and obviously the distance() function doesn't qualify, which can be solved by using the partial() function:

(key=partial(distance, pt))
print(points)
[(3, 4), (1, 2), (5, 6), (7, 8)]

A lot of times what partial() can accomplish, a lambda expression can, in fact, accomplish.

(key=lambda x: distance(pt, x))
print(points)
[(3, 4), (1, 2), (5, 6), (7, 8)]

Above this Python3 implementation to reduce the number of parameters of the callable object is all that I have shared with you.