11# The MIT License
22#
3- # Copyright (c) 2015 Sebastian Ramacher
3+ # Copyright (c) 2015-2021 Sebastian Ramacher
44#
55# Permission is hereby granted, free of charge, to any person obtaining a copy
66# of this software and associated documentation files (the "Software"), to deal
2020# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
2121# THE SOFTWARE.
2222
23- import functools
2423import re
24+ from typing import Optional , Iterator
25+
26+ try :
27+ from functools import cached_property
28+ except ImportError :
29+ from backports .cached_property import cached_property # type: ignore
2530
2631
2732class LazyReCompile :
@@ -30,32 +35,22 @@ class LazyReCompile:
3035 This class allows one to store regular expressions and compiles them on
3136 first use."""
3237
33- def __init__ (self , regex , flags = 0 ) :
38+ def __init__ (self , regex : str , flags : int = 0 ) -> None :
3439 self .regex = regex
3540 self .flags = flags
36- self .compiled = None
37-
38- def compile_regex (method ):
39- @functools .wraps (method )
40- def _impl (self , * args , ** kwargs ):
41- if self .compiled is None :
42- self .compiled = re .compile (self .regex , self .flags )
43- return method (self , * args , ** kwargs )
4441
45- return _impl
42+ @cached_property
43+ def compiled (self ) -> re .Pattern :
44+ return re .compile (self .regex , self .flags )
4645
47- @compile_regex
48- def finditer (self , * args , ** kwargs ):
46+ def finditer (self , * args , ** kwargs ) -> Iterator [re .Match ]:
4947 return self .compiled .finditer (* args , ** kwargs )
5048
51- @compile_regex
52- def search (self , * args , ** kwargs ):
49+ def search (self , * args , ** kwargs ) -> Optional [re .Match ]:
5350 return self .compiled .search (* args , ** kwargs )
5451
55- @compile_regex
56- def match (self , * args , ** kwargs ):
52+ def match (self , * args , ** kwargs ) -> Optional [re .Match ]:
5753 return self .compiled .match (* args , ** kwargs )
5854
59- @compile_regex
60- def sub (self , * args , ** kwargs ):
55+ def sub (self , * args , ** kwargs ) -> str :
6156 return self .compiled .sub (* args , ** kwargs )
0 commit comments