[Pyrex] kw-only arguments?

Sven Berkvens-Matthijsse sven at pyrex.berkvens.net
Thu Sep 20 09:38:28 CEST 2007


> Hi,

Hello,

> is there a way to keep keyword arguments from taking a positional parameter?
> 
> If you have this:
> 
>     def func(a, b, kw1=None, kw2=None):
>          ....
> 
> I can always call it as
> 
>     func(1,2,3,4)
> 
> However, sometimes this is unwanted, as keyword arguments have the
> advantage of not *requiring* a specific position, so they allow me
> to change their appearance in the signature without breaking any
> code (e.g. start using **kwargs in wrappers instead of accepting
> them straight). But if people use them as positional arguments
> (because it's 'convenient'), usually for the first one or two
> arguments, this no longer holds.

I guess the only way to do that, currently, is by using **kwargs and
grabbing the keyword arguments you need from that. You'd also have to
check whether the caller has given a keyword that does not exist.
Something like this ugly piece of code would do what you want,
although not very nicely:

def func(a, b, **kwargs):
    kw1 = kw2 = None
    for __n in kwargs:
        if __n == "kw1":
            kw1 = kwargs[__n]
        elif __n == "kw2":
            kw2 = kwargs[__n]
        else:
            raise TypeError, "Unrecognised keyword argument %s" % __n

    # Do something with kw1 and kw2
    pass

> Stefan

-- 
With kind regards,
Sven



More information about the Pyrex mailing list