is possible to get order of keyword parameters ?

Duncan Booth duncan.booth at invalid.invalid
Fri Jan 25 13:39:31 EST 2008


rndblnch <rndblnch at gmail.com> wrote:

> (sorry, draft message gone to fast)
> 
> i.e. is it possible to write such a function:
> 
> def f(**kwargs):
>     <skipped>
>     return result
> 
> such as :
> f(x=12, y=24) == ['x', 'y']
> f(y=24, x=12) == ['y', 'x']
> 
> what i need is to get the order of the keyword parameters inside the
> function.
> any hints ?
> 
It would be best to do something which makes it obvious to someone reading 
the function call that something magic is going on. Either get people to 
pass a tuple, or if you want you could wrap a tuple in some sugar:

class _OrderedVal(object):
    def __init__(self, name, current):
        self._name = name
        self._current = current
    def __call__(self, value):
        return _Ordered(self._current + ((self._name, value),))
        
class _Ordered(tuple):
    def __init__(self, current=()):
        self._current = current

    def __getattr__(self, name):
        return _OrderedVal(name, self._current)

ordered = _Ordered()

def f(args):
    return [ k for (k,v) in args]

print f(ordered.x(12).y(24))
print f(ordered.y(24).x(12))


The question remains, what use is there for this?



More information about the Python-list mailing list