Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get kwargs Inside Function

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.

like image 638
Mark Avatar asked Jan 18 '10 17:01

Mark


People also ask

How do you get Kwargs from a function in Python?

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 do you use Kwargs in function?

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.

What is Kwargs in a built in function?

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.

How do you beat Kwargs arguments?

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 ( ** ).


1 Answers

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

like image 148
Alex Martelli Avatar answered Sep 22 '22 23:09

Alex Martelli