Multiple optional arguments python -


so have function several optional arguments so:

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

optarg1 & optarg2 usually used , if these 2 args specified optarg3 not used. contrast, if optarg3 specified optarg1 & optarg2 not used. if 1 optional argument it'd easy function "know" argument use:

if optarg1 != none:     else:     else  

my question how "tell" function optional argument use when there's multiple optional arguments , not of them specified? parsing arguments **kwargs way go?

**kwargs used let python functions take arbitrary number of keyword arguments , ** unpacks dictionary of keyword arguments. learn more here

def print_keyword_args(**kwargs):     # kwargs dict of keyword args passed function     print kwargs     if("optarg1" in kwargs , "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'} # needs optarg3! # john doe print_keyword_args(optarg3="maxwell") # {'optarg3': 'maxwell'} # needs optarg1, optarg2!! # maxwell print_keyword_args(optarg1="john", optarg3="duh!") # {'optarg1': 'john', 'optarg3': 'duh!'} # needs optarg1, optarg2!! # duh! 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -