[Python-ideas] re.compile_lazy - on first use compiled regexes

Richard Oudkerk shibturn at gmail.com
Thu Mar 28 15:34:52 CET 2013


An alternative would be to use a lazy proxy.  Given LazyProxy defined as 
below you can use

     pat = LazyProxy(re.compile, r"\w+")

instead of

     pat = re.compile(r"\w+")

This causes a minor slow down (~7%) if you use pat.search() in a loop.

     class LazyProxy(object):
         def __init__(self, func, *args):
             self.__func_args = (func, args)
         def __getattr__(self, name):
             try:
                 obj = object.__getattribute__(self, '__obj')
             except AttributeError:
                 func, args = self.__func_args
                 obj = self.__obj = func(*args)
             res = getattr(obj, name)
             setattr(self, name, res)
             return res

-- 
Richard




More information about the Python-ideas mailing list