Function arguments

Emile van Sebille emile at fenx.com
Thu Oct 18 14:25:28 CEST 2001


"Thomas Heller" <thomas.heller at ion-tof.com> wrote in message
news:9qm3sb$pc43f$1 at ID-59885.news.dfncis.de...
> 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:
>

[snip keyword arg breakout code]

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

Why not?  Because it doesn't delete the key from the dict?

>
> 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

You can write this now:

def popitem(dict, *args):
    if not args:
        return dict.popitem()[1]
    ky = args[0]
    val = dict.get(ky, args[1])
    try: del d[ky]
    except: pass
    return val

def func(*args, **kw):
    defarg1 = popitem(kw, 'defarg1', None)
    defarg2 = popitem(kw, 'defarg2', 0)

As to adding this as a method of dictionary, in 2.2 you can do this as well:

_popitem = popitem
class KW(dictionary):
    def __init__(self, **kwargs):
        self.update(kwargs)
    def popitem(self, *args):
        return _popitem(self, *args)

def func(*args, **kw):
    kw = KW(**kw)
    defarg1 = kw.popitem('defarg1', None)
    defarg2 = kw.popitem('defarg2', 0)

Although I don't see a way to do:

dictionary = KW

d = {1:1,2:2}
print d.popitem(3,3)

Now getting _this_ could be fun!  ( and probably dangerous too ;-)

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list