smartcall.call

smartcall.call(f: Callable[[...], Any], *args: PosOnly | PosOrKw | KwOnly) Any[source]

Call the given function with as many of the given arguments as it can accept.

Parameters:
  • f – The function to call. This can be any callable.

  • args – The arguments to pass to the function. Any number of arguments can be specified. Each argument must be an instance of PosOnly, PosOrKw, or KwOnly. These objects determine how each argument can be passed to the function. Refer to the above links for more details. It’s ok to specify more arguments than the function expects. Any arguments that are incompatible with the given function signature, and that are not marked as “required”, will simply not be used.

Returns:

The result of calling the given function with the given arguments.

Note that inspect.signature() is used to determine which arguments the function expects. If a signature can’t be determined, the function will be called with all of the required arguments and none of the optional ones. This is a problem for a number of built-in functions, including:

See #107161 for more information.

Another potentially confusing case is when the function is wrapped by something that changes its signature. A common example of this is functools.partial(). Consider the following example:

>>> from functools import partial
>>> def f(a, b):
...     return a, b
...
>>> g1 = partial(f, 1)
>>> g2 = partial(f, a=1)

While g1 and g2 both supply the first argument to f, the former does so in a way that allows additional positional arguments to be passed, while the latter doesn’t. In other words, the way that partial() is invoked can affect the signature of the resulting callable.

Example

Invoke a callback function with one required positional argument and several optional keyword arguments:

>>> from smartcall import call, PosOnly, PosOrKw, KwOnly
>>> def my_callback(a, b):
...     return a, b
...
>>> call(
...     my_callback,
...     PosOnly(1, required=True),  # the required argument
...     KwOnly('b', 2),             # the optional arguments
...     KwOnly('c', 3),
... )
(1, 2)