views:

91

answers:

6

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.

+3  A: 

You've specified the parameters in the header?

Why don't you simply use that same info in the body?

def foo(a, b, c):
   params = [a, b, c]

What have I missed?

Oddthinking
This isn't analogous to JavaScript's `arguments` or PHP's `func_get_args()`, which is what I'm looking for.
digitala
I understand that. What is missing is *why* you would want a function like that. What is wrong with using the information you already have?
Oddthinking
+2  A: 

You can create a list out of them using:

args = [a, b, c]

You can easily create a tuple out of them using:

args = (a, b, c)
Michael Aaron Safyan
This isn't analogous to JavaScript's `arguments` or PHP's `func_get_args()`, which is what I'm looking for.
digitala
+3  A: 

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.

Pär Wieslander
Thanks. For anyone else looking to use this method, bear in mind that you should use `locals()` directly after the function definition, otherwise it will contain all variables defined within the function.
digitala
+1  A: 

One solution, using decorators, is here.

Marcelo Cantos
A: 

I would use *args or **kwargs and throw an exception if the arguments are not as expected

Xavier Combelle
That would require lots of testing within the method body, while defining the parameters as part of the function would raise similar errors without any additional tests.
digitala
A: 

You can use the inspect module:

def foo(x):
    return x

inspect.getargspec(foo)
Out[23]: ArgSpec(args=['x'], varargs=None, keywords=None, defaults=None)

This is a duplicate of this and this.

kroger