def get_matcher():
    compiled_regex = compile_my_regex()
match_cache = {}

def try_match(m):
    if m not in match_cache:
        match_cache[m] = compiled_regex.match(m)
return match_cache[m]
return try_match
How to maintain state in Python without classes?