[Python-Dev] Some new additions to functools

SevenInchBread adamadamadamamiadam at gmail.com
Sun Apr 15 12:20:28 CEST 2007


So I've cooked up some very simple functions to add to functools - to expand
it into a more general-purpose module.


def cat(x): return x

class nullfunc(object):
    def __call__(self, *args, **kargs): return self
    def __getattr__(self, name):        return getattr(None, name)

def multimap(func, seq, n=2):
    assert n > 0, "n must be positive"
    if n == 1: return map(func, seq)
    else:       return map(lambda x: multimap(func, x, n-1), seq)

def multifilter(func, seq, n=2):
    return multimap(lambda x: filter(func, x), seq, n-1)

def multireduce(func, seq, n=2):
    return multimap(lambda x: reduce(func, x), seq, n-1)

In an expression, cat achieves the effect of doing nothing - which makes it
a nice default value for some filter-like functions. It's not a huge
improvement - lambda x: x is almost as trivial to define, but I think it
would be nice to have a standard identity function that all of Python could
recognize.

nullfunc is a function that *chomps* away at its input while otherwise
retaining the properties of None - much like the recently proposed callable
None - except not as disasterous to existing practices and potentially more
useful as an optional behavior. This is something that cannot be as quickly
implemented as the cat function.

multimap is a multi-dimensional mapping function that recursively decends a
sequence and applies a function to the data within.

multifilter is a multi-dimensional filter function that recursively descends
a sequence and applies a function to the data within

multireduce - well... you get the idea

A better place to put some of these functions might be __builtin__, so you
don't have to waste time importing something as basic as cat.









-- 
"What's money? A man is a success if he gets up in the morning and goes to
bed at night and in between does what he wants to do." ~ Bob Dylan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-dev/attachments/20070415/0bf125d1/attachment.htm 


More information about the Python-Dev mailing list