monket.samedi-studios.com
Crutcher Dunnavant's Stuff


Technorati search


Made with:
Contact me:
  • crutcher(AT)gmail.com
Monket Info:
Monday 2005-11-07
python toy: kurry
Here's a neat bit of python I worked up for fun the other day. It's a curry function, but it supports keywords as well, I call it kurry. Using kurry, you can do the following sort of things, which is quite useful in python: def foo(a, b, c, d, e): return { 'a': a, 'b': b, 'c': c, 'd': d, 'e': e } bar = kurry(foo, 1, c = 3, d = 4) assert(bar(2, d = 5, e = 6) == foo(1, 2, 3, 5, 6)) The code for kurry makes extensive use of python's variable-argument and keyword mechanisms. The following things are true: def varargs(*args): # *args in param def means collapse args into tuple return args assert(varargs(1,2,3) == (1,2,3)) # *args in function call means expand arg tuple assert(varargs(*(1,2,3)) == (1,2,3)) def varkwargs(**kwargs): # *kwargs in param def means collapse keyword args into dict return kwargs assert(varkwargs(a=1,b=2) == {'a':1, 'b':2}) # **kwargs in function call means use dict as keywords. assert(varkwargs(**{'a':1,'b':2}) == {'a':1, 'b':2}) Here is the code for kurry: def kurry(func, *cargs, **ckwargs): "curry a function, with keyword support" return lambda *largs, **lkwargs: \ func(*(cargs + largs), **dict(ckwargs.items() + lkwargs.items())) We save the positional and keyword arguments at kurry time, and we append the new arguments, and update the keywords at call time.
Misc

Groups

Business

Kick Ass Web Services

Publications

Reference