Paul
Paul

Reputation: 13

Is there a dictionary that contains the function's parameters in Python?

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

Upvotes: 1

Views: 215

Answers (4)

Kenan Banks
Kenan Banks

Reputation: 211980

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.

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599610

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'}

Upvotes: 0

ChristopheD
ChristopheD

Reputation: 116157

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

Upvotes: 7

Kai
Kai

Reputation: 9552

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

Upvotes: 1

Related Questions