Is there any way to pass parameters to a Python function such that if the variable name matches the parameter name, the function will ensure the input is correct?
Let's say I have a function as such:
def func(foo, bar):
return do_something_with(foo, bar)
and I wanted to call it as such:
foo = get_foo()
bar = get_bar()
ret_val = func(foo=foo, bar=bar)
I can do this, but I feel like when the parameter name and the variable name are the same, there should be some mechanism to automatically match up the parameters (like NATURAL JOIN in SQL). Is there any such mechanism?
* is the usual way of doing this, forcing the caller to provide names for the arguments
def func(*, foo, bar)
see PEP 3102 – Keyword-Only Arguments (*) and PEP 570 – Python Positional-Only Parameters
(/) for the inverse
You might also consider using a dict **kwargs which forces the input to have the correct keys
def func(**kwargs):
foo = kwargs.pop("foo")
bar = kwargs.pop("bar")
if kwargs:
raise ValueError(f"unexpected unused arguments: {kwargs}")
...
Practically popping from kwargs can be useful to maintain Python 2.x compatibility or potentially help transition legacy callers (for example by also accepting a subset of positional or *args and warning for members), but prefer PEP 3102 * if you can (available in every version of Python 3)!
However, generally, don't try to "force" or "help" callers of your function use it properly and leave how they call it up to them!
Python's flexibility goes both ways and callers can easily get the signature right by simply providing the arguments if they want to, or misuse your function in surprising ways, such as calling inspect.getsource() dynamically rewriting your function and clobbering the original name
That said, also try not to break callers in non-obvious ways if you're writing a library, say by switching the order of two inputs of the same type and not validating them!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With