ordered keywords?

Ron Adam rrr at ronadam.com
Mon Oct 17 13:51:16 EDT 2005


Is there a way to preserve or capture the order which keywords are given?

 >>> def foo(**kwds):
...    print kwds
...
 >>> foo(one=1, two=2, three=3)
{'three': 3, 'two': 2, 'one': 1}


I would love to reverse the *args, and **kwds as well so I can  use kwds 
to set defaults and initiate values and args to set the order of 
expressions.


def foo(**__dict__, *args):
       print args

print foo(x=10, y=20, x, y, x+y)
[10, 20, 30]


Ok, I know there is a lot of problems with that.  The reason I would 
like it is because I think there might be a use case for it where a 
function iterates over *args in order, but uses kwds to set values.

def drawshapes(**inits, *args):
     for obj in args:
         obj.draw()

drawshapes( triangle=3, square=4, color=red,
             polygon(triangle, color),
             polygon(square, color) )

This comes close to the same pattern used in SVG and other formats where 
you have definitions before expressions.  If I use keywords only, It 
won't keep the order, and if I use args before keywords, I have to 
pre-assign temporary 'None' values to the arguments in the parent or 
global scope.

Any ideas?

Cheers,
    Ron


























More information about the Python-list mailing list