OLD | NEW |
| (Empty) |
1 #!/usr/bin/env python | |
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved. | |
3 # Use of this source code is governed by a BSD-style license that can be | |
4 # found in the LICENSE file. | |
5 | |
6 '''In GRIT, we used to compile a lot of regular expressions at parse | |
7 time. Since many of them never get used, we use lazy_re to compile | |
8 them on demand the first time they are used, thus speeding up startup | |
9 time in some cases. | |
10 ''' | |
11 | |
12 import re | |
13 | |
14 | |
15 class LazyRegexObject(object): | |
16 '''This object creates a RegexObject with the arguments passed in | |
17 its constructor, the first time any attribute except the several on | |
18 the class itself is accessed. This accomplishes lazy compilation of | |
19 the regular expression while maintaining a nearly-identical | |
20 interface. | |
21 ''' | |
22 | |
23 def __init__(self, *args, **kwargs): | |
24 self._stash_args = args | |
25 self._stash_kwargs = kwargs | |
26 self._lazy_re = None | |
27 | |
28 def _LazyInit(self): | |
29 if not self._lazy_re: | |
30 self._lazy_re = re.compile(*self._stash_args, **self._stash_kwargs) | |
31 | |
32 def __getattribute__(self, name): | |
33 if name in ('_LazyInit', '_lazy_re', '_stash_args', '_stash_kwargs'): | |
34 return object.__getattribute__(self, name) | |
35 else: | |
36 self._LazyInit() | |
37 return getattr(self._lazy_re, name) | |
38 | |
39 | |
40 def compile(*args, **kwargs): | |
41 '''Creates a LazyRegexObject that, when invoked on, will compile a | |
42 re.RegexObject (via re.compile) with the same arguments passed to | |
43 this function, and delegate almost all of its methods to it. | |
44 ''' | |
45 return LazyRegexObject(*args, **kwargs) | |
OLD | NEW |