Python-based regular expression parser that allows patterns to call functions?

castironpi at gmail.com castironpi at gmail.com
Sun Mar 2 11:01:03 EST 2008


On Mar 2, 8:41 am, Andrew Warkentin <andr... at datanet.ab.ca> wrote:
> I am writing a filtering HTTP proxy (the site ishttp://xuproxy.sourceforge.net/). I want it to be compatible with
> Proxomitron (http://proxomitron.info/) filters. I need a regular
> expression parser that allows patterns to call functions (or more
> likely, class methods), to implement "matching commands" (look at the
> Proxmitron documentation to see what I mean). Does anyone know if such a
> library exists for Python, or do I have to write my own parser?

To make a list of commands available:

class C:
   def behavior( self ): pass
   def behavior2( self ): pass
   cmds= [ behavior, behavior2 ]

Then search C.cmds for a match to the regular expression.
C.behavior.func_name contains the string 'behavior' for checking.  You
might need to "bind" the contents of C.cmds before you call them too.
More info available, just ask.

You can also do:

class C:
   @string_callable
   def behavior( self ): pass
   @string_callable
   def behavior2( self ): pass

and

class C:
   def behavior( self ): pass
   def behavior2( self ): pass
   cmds= [ 'behavior', 'behavior2' ]

(strings this time), and use getattr( C, 'behavior' ) or for c= C(),
getattr( c, 'behavior' ).

class C:
   def behavior( self ): pass
   def behavior2( self ): pass
   cmds= [ 'behavior', 'behavior2' ]
C.cmds= commandmap( C, C.cmds )

can generate a dictionary of strings to methods.  And there's always

getattr( c, strA ), for your choice of strA, which throws an exception
if strA is not an attribute (method or property) of c, and hasattr( c,
strA ) can test if it is.

You less often want to generate distinct functions based on parameters
only, but you can.

c= C()
def behavior3( self ): pass
c.behavior3= behavior3

so c.behavior3() is legal.

Where does that get you?



More information about the Python-list mailing list