Get kwargs Inside Function

Mark picture Mark · Jan 18, 2010 · Viewed 13.5k times · Source

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.

Answer

Alex Martelli picture Alex Martelli · Jan 18, 2010

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;-).