3

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 something like this

def myFunc(*args, optDefault=1):

But this just gives a syntax error. Is there an equivalent way to do this?

highBandWidth
  • 16,751
  • 20
  • 84
  • 131

3 Answers3

2

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.

Klaas van Schelven
  • 2,374
  • 1
  • 21
  • 35
  • assert not(kwargs) is a better idiom ;) – GaretJax Aug 01 '11 at 17:46
  • GaretJax: I suppose that's a matter of taste :-) Not as a function? Yuck! – Klaas van Schelven Aug 01 '11 at 17:48
  • 1
    Things like that should result in a `TypeError`, not in an `AssertionError`. And yes, `not kwargs` is more idiomatic (although polymorphism doesn't matter here much, it's a pretty save bet to assume `type(kwarg) is dict`). –  Aug 01 '11 at 17:54
1

What about:

def myFunc(optDefault=1, *args):
GaretJax
  • 7,462
  • 1
  • 38
  • 47
-2

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
Areza
  • 5,623
  • 7
  • 48
  • 79
  • 1
    optparse [is deprecated](http://docs.python.org/library/optparse.html) and it was intended for another usage (parse command line options). – Paolo Aug 01 '11 at 18:04