Skip to content Skip to sidebar Skip to footer

Having Arbitrary Number Of Arguments With A Named Default In Python

I want to write a function in python that can take an arbitrary number of unnamed arguments in addition to one named argument (with a default). For example, I want to write somethi

Solution 1:

What about

def myFunc(*args, **kwargs):
    optDefault = kwargs.pop('optDefault', 1)
    assert kwargs == {}, "There may only be one keyword argument to myFunc"

Not the prettiest, but it works.


Solution 2:

What about:

def myFunc(optDefault=1, *args):

Solution 3:

why dont you use this, an example (I borrow from here)

import optparse

if __name__=="__main__":
    parser = optparse.OptionParser("usage: %prog [options] arg1 arg2")
    parser.add_option("-H", "--host", dest="hostname",
                      default="127.0.0.1", type="string",
                      help="specify hostname to run on")
    parser.add_option("-p", "--port", dest="portnum", default=80,
                      type="int", help="port number to run on")

    (options, args) = parser.parse_args()
    if len(args) != 2:
        parser.error("incorrect number of arguments")
    hostname = options.hostname
    portnum = options.portnum

Post a Comment for "Having Arbitrary Number Of Arguments With A Named Default In Python"