tags:

views:

87

answers:

4

I'd like to be able to get a dictionary of all the parameters passed to a function.

def myfunc( param1, param2, param3 ):
    print 'Param1=%(param1)s, Param2=%(param2)s Param3=%(param3)' % __method_param_dict__

So my question is does the dictionary method_param_dict exist, and if so what is it called.

Thanks

+1  A: 

You can do:

def myfunc(*args, **kwargs):
  # Now "args" is a list containing the parameters passed
  print args[0], args[1], args[2]

  # And "kwargs" is a dictionary mapping the parameter names passed to their values
  for key, value in kwargs.items():
    print key, value
Kai
+3  A: 

If you need to do that, you should use *args and **kwargs.

def foo(*args, **kwargs):
   print args
   print kwargs

foo(1,2,3,four=4,five=5)
# prints [1,2,3] and {'four':4, 'five':5}

Using locals() is also a possibility and will allow you to iterate through the names of position arguments, but you must remember to access it before defining any new names in the scope, and you should be aware that it will include self for methods.

Triptych
+7  A: 

A solution for your specific example:

def myfunc(param1, param2, param3):
    dict_param = locals()

But be sure to have a look at this article for a complete explanation of the possiblities (args, kwargs, mixed etc...)

ChristopheD
+1 as the specific example's argument positioning may have been important, and everyone forgets locals().
Jed Smith
Thanks Jed - I've been staring at my Python Cookbook and Google to find that answer!I was aware of *args and *kwargs, but I don't want a variable arg list, just a shorthand to stop me having to type the args all over again.
Paul
Oops - the thanks should have been to ChristopheD - apologies and thanks.
Paul
A: 

If you want to accept variable parameters, you can use *args and **kwargs.

*args is a list of all non-keyword parameters. **kwargs is a dictionary of all keyword parameters. So:

def myfunc(*args, **kwargs):
    if args:
       print args
    if kwargs:
       print kwargs


>>> myfunc('hello', 'goodbye')
('hello', 'goodbye')

>>> myfunc(param1='hello', param2='goodbye')
{'param1': 'param2', 'param2': 'goodbye'}
Daniel Roseman