Created
July 17, 2024 22:53
-
-
Save JacobFV/1a071793d956a4c8b71331a096f3d95c to your computer and use it in GitHub Desktop.
call_with_appropriate_args.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def call_with_appropriate_args(fn, *args, **kwargs): | |
""" | |
Call a function with only the arguments it can accept. | |
This function inspects the signature of the given function and calls it with | |
only the arguments that match its parameters. It filters out any excess | |
arguments that are not part of the function's signature. | |
Args: | |
fn (callable): The function to be called. | |
*args: Positional arguments to be passed to the function. | |
**kwargs: Keyword arguments to be passed to the function. | |
Returns: | |
The result of calling the function with the filtered arguments. | |
Example: | |
def example_func(a, b): | |
return a + b | |
result = call_with_appropriate_args(example_func, a=1, b=2, c=3) | |
# result will be 3, and 'c' will be ignored | |
""" | |
sig = inspect.signature(fn) | |
bound_args = sig.bind_partial(*args, **kwargs) | |
bound_args.apply_defaults() | |
# Filter out excess arguments | |
filtered_args = { | |
k: v for k, v in bound_args.arguments.items() if k in sig.parameters | |
} | |
return fn(**filtered_args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment