Given the following function:
def foo(a, b, c): pass
How would one obtain a list/tuple/dict/etc of the arguments passed in, without having to build the structure myself?
Specifically, I'm looking for Python's version of JavaScript's arguments
keyword or PHP's func_get_args()
method.
What I'm not looking for is a solution using *args
or **kwargs
; I need to specify the argument names in the function definition (to ensure they're being passed in) but within the function I want to work with them in a list- or dict-style structure.
The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.
A tuple can also be passed as a single argument to the function. Individual tuples as arguments are just individual variables. A function call is not an assignment statement; it's a reference mapping.
1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.
Passing Dictionary as kwargs It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn't have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.
You can use locals()
to get a dict of the local variables in your function, like this:
def foo(a, b, c): print locals() >>> foo(1, 2, 3) {'a': 1, 'c': 3, 'b': 2}
This is a bit hackish, however, as locals()
returns all variables in the local scope, not only the arguments passed to the function, so if you don't call it at the very top of the function the result might contain more information than you want:
def foo(a, b, c): x = 4 y = 5 print locals() >>> foo(1, 2, 3) {'y': 5, 'x': 4, 'c': 3, 'b': 2, 'a': 1}
I would rather construct a dict or list of the variables you need at the top of your function, as suggested in the other answers. It's more explicit and communicates the intent of your code in a more clear way, IMHO.
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