Shell-like Decorators

Joel Bender jjb5 at
Wed Jan 18 23:22:21 CET 2006

I was inspired by shell-like processing mentioned here:


and created a decorator version below.  I've been using it for parsing
a pile of C include files and building digraphs of the results.  For
example, given jdir('*.h') returns a sequence of file names:

     jdir("*.h") | jimap(file) | jchain \
       | jmatch(r"^#define\s+(\w+)\s+(\d+)") | jdict

builds a dictionary of the #define's in the files.  Comments?


---------- Code Bits ----------

import re
import sys

from itertools import imap, ifilter, chain


class _jcall:

     def __init__(self, f):
         self.fn = f

     def __ror__(self, input):
         return self.fn(input)

     def __call__(self, *args, **kwargs):
         return self.fn(*args, **kwargs)

def jcall(f):
     return _jcall(f)

jlist = jcall(list)
jtuple = jcall(tuple)
jdict = jcall(dict)
jchain = jcall(lambda input: chain(*input))


def jiter(iterfn):

     def iterwrap(f = None):

         class _jiter(_jcall):

             def __ror__(self, input):
                 return iterfn(self.fn, input)

         return _jiter(f)

     return iterwrap

jmap = jiter(map)
jfilter = jiter(filter)
jimap = jiter(imap)
jifilter = jiter(ifilter)
jreduce = jiter(reduce)


def japply(f):

     class _japply(_jcall):

         def __ror__(self, input):
             for item in input:

     return _japply(f)

def writelines(f):
     return japply(f.write)

printlines = writelines(sys.stdout)


import re

def jgrep(pat):
     return jifilter(re.compile(pat).search)

def jmatch(pat):
     expr = re.compile(pat)

     def matchfn(input):
         for item in input:
             m = expr.match(item)
             if m: yield m.groups()

     return jcall(matchfn)

def jsub(pat,repl):
     expr = re.compile(pat)
     return jimap(lambda x: expr.sub(repl, x))

More information about the Python-list mailing list