From 9ece6742b14cc7773c048bef35711b5e060d80f6 Mon Sep 17 00:00:00 2001 From: Marcel Bargull Date: Fri, 16 Mar 2018 19:51:00 +0100 Subject: evaluate re.compile lazily --- util.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'util.py') diff --git a/util.py b/util.py index 9f939cf..077b264 100644 --- a/util.py +++ b/util.py @@ -6,6 +6,9 @@ some helper functions that might be generally useful from __future__ import absolute_import, print_function +from functools import partial +import re + from .compat import text_type, binary_type if False: # MYPY @@ -13,6 +16,26 @@ if False: # MYPY from .compat import StreamTextType # NOQA +class LazyEval(object): + def __init__(self, func, *args, **kwargs): + def lazy_self(): + return_value = func(*args, **kwargs) + object.__setattr__(self, "lazy_self", lambda: return_value) + return return_value + object.__setattr__(self, "lazy_self", lazy_self) + + def __getattribute__(self, name): + lazy_self = object.__getattribute__(self, "lazy_self") + if name == "lazy_self": + return lazy_self + return getattr(lazy_self(), name) + + def __setattr__(self, name, value): + setattr(self.lazy_self(), name, value) + + +RegExp = partial(LazyEval, re.compile) + # originally as comment # https://github.com/pre-commit/pre-commit/pull/211#issuecomment-186466605 # if you use this in your code, I suggest adding a test in your test suite -- cgit v1.2.1 From 5cc97a07737bf08ccce187e04026002e62ce977f Mon Sep 17 00:00:00 2001 From: Marcel Bargull Date: Sat, 17 Mar 2018 00:00:56 +0100 Subject: add doc string for util.LazyEval --- util.py | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'util.py') diff --git a/util.py b/util.py index 077b264..7a66947 100644 --- a/util.py +++ b/util.py @@ -17,6 +17,15 @@ if False: # MYPY class LazyEval(object): + """ + Lightweight wrapper around lazily evaluated func(*args, **kwargs). + + func is only evaluated when any attribute of its return value is accessed. + Every attribute access is passed through to the wrapped value. + (This only excludes special cases like method-wrappers, e.g., __hash__.) + The sole additional attribute is the lazy_self function which holds the + return value (or, prior to evaluation, func and arguments), in its closure. + """ def __init__(self, func, *args, **kwargs): def lazy_self(): return_value = func(*args, **kwargs) -- cgit v1.2.1