import re
class _Lazy(object):
__slots__ = ['pattern', 'kwargs', 'compiled']
def __init__(self, pattern, **kwargs):
self.pattern = pattern
self.kwargs = kwargs
self.compiled = None
def __getattr__(self, name):
if self.compiled is None:
self.compiled = re.compile(self.pattern, **self.kwargs)
return self.compiled.__getattribute__(name)
def lazy_compile(pattern, **kwargs):
return _Lazy(pattern, **kwargs)
Use:
In [2]:
In [2]: lazy_compile(r'[a-z]')
Out[2]: <__main__._Lazy at 0x11095c088>
In [3]: c = lazy_compile(r'[a-z]')
In [4]: c.findall('sdsd sdsds aq, $A fddf')
Out[4]: ['s', 'd', 's', 'd', 's', 'd', 's', 'd', 's', 'a', 'q', 'f', 'd', 'd', 'f']
Комментариев нет:
Отправить комментарий