Last active
January 10, 2022 21:25
-
-
Save kissgyorgy/ee1c27fc39cbf69a8459d2a38beb1491 to your computer and use it in GitHub Desktop.
Python: lazily evaluate field for structlog
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LazyField: | |
"""Evaluates __repr__ lazily for heavy calculations. | |
Expects callable with args and kwargs of how to calculate the value. | |
""" | |
def __init__(self, func, *args, **kwargs): | |
self._func = func | |
self._args = args | |
self._kwargs = kwargs | |
self._value = ... | |
def __repr__(self): | |
if self._value is ...: | |
value = self._func(*self._args, **self._kwargs) | |
self._value = value | |
return self._value | |
# Usage: | |
import structlog | |
def expensive_computation(base, *, exponent): | |
return base**exponent | |
logger = structlog.get_logger() | |
logger.debug("Event", lazy_field=LazyField(expensive_computation, 2, exponent=1000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment