Shell-like Decorators

J

Joel Bender

I was inspired by shell-like processing mentioned here:

<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/276960>

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?


Joel

---------- 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:
self.fn(item)

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))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top