[Python-Dev] Function arguments (original) (raw)

Thomas Heller thomas.heller@ion-tof.com
Thu, 18 Oct 2001 10:28:58 +0200


Call me weird, but sometimes I need functions taking a number of positional arguments, some named arguments with default values, and other named arguments as well.

Something like this (which does not work):

def function(*args, defarg1=None, defarg2=0, **kw): ...

The usual way to program this is:

def function(*args, ***kw): if kw.has_key('defarg1'): defarg1 = kw['defarg1'] del kw['defarg1'] else: defarg1 = None

if kw.has_key('defarg2'):
    defarg1 = kw['defarg2']
    del kw['defarg2']
else:
    defarg2 = 0

# ...process the positional arguments in args
# ...process the remaining named arguments in kw

Doesn't look very pretty IMO, and using the dictionaries' get method doesn't help.

I was thinking of a popitem() dictionary method taking (optionally) 2 arguments: the name of the item to pop, and the default value to return if the item is not present in the dictionary:

d = {'a': 2, 'b': 3} d.popitem('defarg', 0) 0 d {'a': 2, 'b': 3} d.popitem('a', 100) 2 d {'b': 3}

Opinions?

Thomas