16

So I have a function with several optional arguments like so:

def func1(arg1, arg2, optarg1=None, optarg2=None, optarg3=None):

Optarg1 & optarg2 are usually used together and if these 2 args are specified then optarg3 is not used. By contrast, if optarg3 is specified then optarg1 & optarg2 are not used. If it were one optional argument it'd be easy for the function to "know" which argument to use:

if optarg1 != None:
    do something
else:
    do something else 

My question is how to I "tell" the function which optional argument to use when there's multiple optional arguments and not all of them are always specified? Is parsing the arguments with **kwargs the way to go?

1

2 Answers 2

20

If you assign them in the call of the function you can pre-empt which parameter you are passing in.

def foo( a, b=None, c=None):
    print("{},{},{}".format(a,b,c))

>>> foo(4) 
4,None,None
>>> foo(4,c=5)
4,None,5
Sign up to request clarification or add additional context in comments.

Comments

19

**kwargs is used to let Python functions take an arbitrary number of keyword arguments and then ** unpacks a dictionary of keyword arguments. Learn More here

def print_keyword_args(**kwargs):
    # kwargs is a dict of the keyword args passed to the function
    print kwargs
    if("optarg1" in kwargs and "optarg2" in kwargs):
        print "Who needs optarg3!"
        print kwargs['optarg1'], kwargs['optarg2']
    if("optarg3" in kwargs):
        print "Who needs optarg1, optarg2!!"
        print kwargs['optarg3']

print_keyword_args(optarg1="John", optarg2="Doe")
# {'optarg1': 'John', 'optarg2': 'Doe'}
# Who needs optarg3!
# John Doe
print_keyword_args(optarg3="Maxwell")
# {'optarg3': 'Maxwell'}
# Who needs optarg1, optarg2!!
# Maxwell
print_keyword_args(optarg1="John", optarg3="Duh!")
# {'optarg1': 'John', 'optarg3': 'Duh!'}
# Who needs optarg1, optarg2!!
# Duh!

2 Comments

This is the most Pythonic way of doing this.
What's the advantage of using kwargs here? You might as well do if optarg1 is not None and optarg2 is not None... This way the arguments of the function are at least clear. Using kwargs exclusively, it is not clear what arguments it's even expecting...

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.