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.
Note that
inspect.signature()is used to determine which arguments the function expects. This might not work as expected if the function is wrapped by something that changes its signature. A common example of this isfunctools.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
g1andg2both supply the first argument tof, 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 thatpartial()is invoked can affect the signature of the resulting 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, orKwOnly. These objects determine how each argument can be passed to the function. Refer to the above links for more details. Positional argument are preferred, when there’s an option, because they don’t require that the function use the same argument names as the caller.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.
Example
Invoke a callback function with one required positional argument and several optional keyword arguments:
>>> from smartcall import PosOnly, PosOrKw, KwOnly, call >>> 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=2), ... ) (1, 2)