1

I followed this to pass functions as arguments:

Passing functions with arguments to another function in Python?

However, I could not figure out how to pass function with its own arguments as names parameters

def retry(func, *args):
  func(*args)

def action(args):
  do something

retry(action, arg1, namedArg=arg2)

Here I get an exception:

TypeError: retry() got an unexpected keyword argument 'namedArg'

Normally, I can do:

action(arg1, namedArg=arg2)

Please help/

Community
  • 1
  • 1
GJain
  • 5,025
  • 6
  • 48
  • 82

3 Answers3

3

*args and it's sibling **kwargs are the names generally used for extra arguments and key word arguments. You are passing a kew word argument when you pass namedArg=arg2.

So, try this instead:

def retry(func, *args, **kwargs):
  func(*args, **kwargs)

def action(*args, **kwargs):
  do something

retry(action, arg1, namedArg=arg2)

If you instead use

def action(args, kwargs):
  do something

Then you will end up with args as a list of arguments and kwargs as a dictionary of key word arguments, so in your case

args = [arg1]
kwargs = {'namedArg':arg2}
sberry
  • 128,281
  • 18
  • 138
  • 165
  • How do I ensure the order of arguments in the target function? Let m try this? thx for quick repsonse – GJain Jul 22 '13 at 04:17
  • 2
    The order of the arguments in the list will be same as the order passed. The key word args are a dictionary, so there is no order. – sberry Jul 22 '13 at 04:20
0

Read this, keyword arguments in python doc.

As the error clearly states that got an unexpected keyword argument 'namedArg'. where as you are providing only arguments in *args.

You will find plenty of examples to understand keyword arguments.

iamkhush
  • 2,562
  • 3
  • 20
  • 34
0

What you need is functools.

http://docs.python.org/2/library/functools.html#functools.partial

from functools import partial

def action(arg):
    do something

def action2(arg=1):
    do something

def action3(arg1, arg2=2):
    do something

partial(action, arg1)

partial(action, arg1, arg2=3)
sberry
  • 128,281
  • 18
  • 138
  • 165
solos
  • 61
  • 1
  • 7
  • In general you would be right, but the point of the `retry()` function seems to be to repeat the function call if it didn't succeed. In your case, one could give the result of `partial()` to that function and have it call it just like it is. But that doesn't become clear from what you wrote. – glglgl Jul 22 '13 at 06:00