RFC: Assignment as expression (pre-PEP)

Duncan Booth duncan.booth at invalid.invalid
Fri Apr 6 05:04:12 EDT 2007


"Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> wrote:

> You have to build the handlers list, containing (regex, handler) items;  
> the "unknown" case might be a match-all expression at the end.
> Well, after playing a bit with decorators I got this:
<snip>

That's a nice class, and more maintainable with the separate handler 
methods than a long function. Here's a completely untested variation. I 
hope the intent is clear:

     def handle_this(regex, handlers=handlers):
         # A decorator; associates the function to the regex
         # (Not intended to be used as a normal method!
         # not even a static method!)
         def register(function, regex=regex):
             handlers.append((function.__name__, regex))
             return function
         return register

      ... insert handlers here ...

    	def parse(self):
         regex = '|'.join(['(?P<%s>%s)' % pair for pair in self.handlers])
         fields = str.split(self.name)
         for field in fields:
             match = regex.match(field)
             if match:
                 handler = getattr(self,
                    match.lastgroup,
                    self.handle_unknown)
    	    	    	handler(self, field, match)

The handler functions themselves would have to be constrained to also use 
only named groups, but you gain by only having a single regex.match call on 
each field which could (if there are a lot of handlers) be significant.

The calculation of regex could also of course be pulled out of parse to 
somewhere it only happens once for the class instead of once per instance.



More information about the Python-list mailing list