faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes

Entry

papply (was: A little present)

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 375, Michael Hudson


"""
Packages: functional_programming
"""
"""
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)