diff options
author | Anthon van der Neut <anthon@mnt.org> | 2018-06-16 23:41:43 +0200 |
---|---|---|
committer | Anthon van der Neut <anthon@mnt.org> | 2018-06-16 23:41:43 +0200 |
commit | 15008733ed560cb506871f1c4fac99c99e53bfe6 (patch) | |
tree | a30c9db2939a72720bac131b8b2075c9d72be500 /util.py | |
parent | 6805e6c06a7255f737d13efc9e1002ff6f254039 (diff) | |
parent | 13cd9b56e285a0ddf4c64e4c5347485bd9ec6546 (diff) | |
download | ruamel.yaml-15008733ed560cb506871f1c4fac99c99e53bfe6.tar.gz |
merge PR27 improving startup time0.15.39
Diffstat (limited to 'util.py')
-rw-r--r-- | util.py | 33 |
1 files changed, 33 insertions, 0 deletions
@@ -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,36 @@ if False: # MYPY from .compat import StreamTextType # NOQA +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) + 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 |