4

Suppose I have a function with 10 args:

def foo(arg1,arg2,arg3,arg4.....):

Sometimes, I need to call it with only arg1 and another time arg1, arg4, or arg4 , arg7.

My program doesn't specify the type of the function call. Does python have a way to help me?

2
  • Use default argument parameters Commented Aug 25, 2013 at 9:31
  • def foo(arg1 = val, arg2 = val2, arg3 = val3,...): Commented Aug 25, 2013 at 9:32

3 Answers 3

14

One way to do it is to make the parameters optional:

def foo(arg1=None,arg2=None,arg3=None...)

which can be called like this:

foo(arg1=1,arg3=2)

or like this:

a = {'arg1':1, 'arg3':2}
foo(**a)

If this list of parameters is spinning out of control you could simply use **kwargs to let your function take an optional number of (named) keyword arguments:

def foo(**kwargs):
    print kwargs

params = {'arg1':1, 'arg2':2}

foo(**params)         # Version 1
foo(arg1=3,arg2=4)    # Version 2

Output:

{'arg1': 1, 'arg2': 2}
{'arg1': 3, 'arg2': 4}

Note: You can use one asterisk (*) for an arbitrary number of arguments that will be wrapped up in a tuple.

Sign up to request clarification or add additional context in comments.

2 Comments

What if there is a variable named "arg1", identically named as the optional parameter in foo(), outside of foo()? Will it cause conflict?
no, it won't cause conflict Sean. I think you're describing foo(arg1=arg1). Python interpreters know the token to the left of '=' refers to the name of the param.
5

Give your args a default value like None:

def foo(arg1=None, arg2=None, ..., arg10=None):

Now, when calling the function pass a dictionary of keyword arguments:

kwargs = {
    'arg1': 'test',
    'arg7': 'test2',
}

foo(**kwargs)

It's equivalent to:

foo('test', None, None, None, ..., 'test2', None, None, None)

Or, to be more specific:

foo(arg1='test', arg7='test2')

Comments

0

You could use keyword arguments

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.