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.
You can use
locals()to get a dict of the local variables in your function, like this: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: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.