A little present.

Michael Hudson mwh21 at cam.ac.uk
Mon Feb 14 14:19:08 EST 2000


I hope someone finds this useful. It's a little hack I threw together
to save some keystrokes in interactive mode. As such it does very
little error checking.

I found myself testing a function of two arguments:

def t(a,p=...):
    ...

over a range of inputs, so I was typing things like

>>> map(t,range(10))

and looking at the result; this was fine until I wanted to put
something else in the optional second parameter; my only recourse was
to type

>>> map(lambda a:t(a,73),range(10))

This jarred sufficiently (and reminded me of other irritating
situations in the past) that I cooked up the appended script, allowing
me to do this:

>>> from papply import X
>>> map(X(t,(),73),range(10))

The idea is that after a call to X(func,...) there are a number of
`holes' (notated by an empty tuple) in the arglist that can be `filled
in' by subsequent calls (to what X returns). This means you can't
presupply the empty tuple to func, but I couldn't think of a better
way.

It's a bit like currying, but more general.

I've stuck 

from papply import X

into my ~/.pythonrc, and I think I'll find it handy. I hope you do
too.

Cheers,
Michael

--- papply.py starts here ---
class X:
    def __init__(self,func,*args):
        self.func = func
        self.args = []
        self.mapping = {}
        hole = 0
        for i in range(len(args)):
            if args[i] == ():
                self.args.append( None )
                self.mapping[hole] = i
                hole = hole + 1
            else:
                self.args.append( args[i] )
    def __call__(self,*args):
        realargs = self.args[:]
        for i in range(len(args)):
            realargs[self.mapping[i]] = args[i]
        return apply(self.func,realargs)





More information about the Python-list mailing list