If I have a python function like so:
def some_func(arg1, arg2, arg3=1, arg4=2):
Is there a way to determine which arguments were passed by keyword from inside the function?
EDIT
For those asking why I need this, I have no real reason, it came up in a conversation and curiosity got the better of me.
To pass a variable-length keyword argument to a function in Python, use the **kwargs. To represent kwargs, we denote with a double asterisk ** before the parameter name.
How to Use **kwargs in Python. **kwargs allows us to pass a variable number of keyword arguments to a Python function. In the function, we use the double-asterisk ( ** ) before the parameter name to denote this type of argument.
For this problem Python has got a solution called **kwargs , it allows us to pass the variable length of keyword arguments to the function. In the function, we use the double asterisk ** before the parameter name to denote this type of argument.
Kwargs allow you to pass keyword arguments to a function. They are used when you are not sure of the number of keyword arguments that will be passed in the function. Kwargs can be used for unpacking dictionary key, value pairs. This is done using the double asterisk notation ( ** ).
No, there is no way to do it in Python code with this signature -- if you need this information, you need to change the function's signature.
If you look at the Python C API, you'll see that the actual way arguments are passed to a normal Python function is always as a tuple plus a dict -- i.e., the way that's a direct reflection of a signature of *args, **kwargs
. That tuple and dict are then parsed into specific positional args and ones that are named in the signature even though they were passed by name, and the *a
and **kw
, if present, only take the "overflow" from that parsing, if any -- only at this point does your Python code get control, and by then the information you're requesting (how were the various args passed) is not around any more.
To get the information you requested, therefore, change the signature to *a, **kw
and do your own parsing/validation -- this is going "from the egg to the omelette", i.e. a certain amount of work but certainly feasible, while what you're looking for would be going "from the omelette back to the egg"... simply not feasible;-).
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