how to pass a custom object to re.search?

Peter Otten __peter__ at web.de
Fri Aug 17 10:51:48 EDT 2007


 brunovianarezende at gmail.com wrote:

> I've done that (and added __unicode__ too). I only didn't want to, I
> want to do:
> 
> re.search(custom_object)
> 
> so, code that worked before as:
> 
> re.search(parentobj.custom_object)
> 
> don't have to be changed for:
> 
> re.search(str(parentobj.custom_object))
> 
> and I'm also curious to know if it is possible to do that... :-)

Not without monkeypatching the re module:

import re

_original_compile = re._compile

def _wrapped_compile(*key):
    try:
        custom_compile = key[0].__compile__
    except AttributeError:
        return _original_compile(*key)
    else:
        return custom_compile(*key[1:])

re._compile = _wrapped_compile


class Aaa(object):
    def __compile__(self, *args):
        return re.compile("[Aa]+")

print re.findall(Aaa(), "a yadda so whaaaat")

Peter



More information about the Python-list mailing list