Function arguments

Thomas Heller thomas.heller at ion-tof.com
Thu Oct 18 08:56:41 EDT 2001


"Emile van Sebille" <emile at fenx.com> wrote in message news:9qmi0b$oab8c$1 at ID-11957.news.dfncis.de...
>
> "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?
Exactly - what I want is a 'destructive get method' (Maybe
a name other than popitem() would be better).

>
> >
> > 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:
>
[description of extended popitem snipped]

>
> As to adding this as a method of dictionary, in 2.2 you can do this as well:
>
[snip again]

> Although I don't see a way to do:
>
> dictionary = KW
>
> d = {1:1,2:2}
> print d.popitem(3,3)
You could do:
d = {1:1,2:2}
d = KW(d)
print d.popitem(3,3)

For the solution to my problem, I came up with this
which is at least compact:

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


Thomas





More information about the Python-list mailing list