1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 03:24:20 +00:00

Add Lazy object (undocumented)

This commit is contained in:
Steffo 2020-11-30 03:04:04 +01:00
parent 3457f05ec0
commit c7bca2cbcf
6 changed files with 91 additions and 0 deletions

View file

@ -0,0 +1,9 @@
Lazy autodoc
=================
.. note:: The documentation for this section hasn't been written yet.
.. currentmodule:: royalnet.lazy
.. automodule:: royalnet.lazy
:members:
:undoc-members:

0
royalnet/__init__.py Normal file
View file

View file

@ -0,0 +1 @@
from .lazy import *

46
royalnet/lazy/lazy.py Normal file
View file

@ -0,0 +1,46 @@
from __future__ import annotations
from royalnet.typing import *
import functools
Result = TypeVar("Result")
class Lazy:
def __init__(self, obj: Callable[[Any], Result], *args, **kwargs):
self._func: Callable[[Any], Result] = obj
self._args = args
self._kwargs = kwargs
self.evaluated = False
self._result = None
def _evaluate_args(self) -> List[Any]:
evaluated_args = []
for arg in self._args:
if isinstance(arg, Lazy):
arg = arg.evaluate()
evaluated_args.append(arg)
return evaluated_args
def _evaluate_kwargs(self) -> Dict[str, Any]:
evaluated_kwargs = {}
for key, value in self._kwargs.items():
if isinstance(value, Lazy):
value = value.evaluate()
evaluated_kwargs[key] = value
return evaluated_kwargs
def evaluate(self) -> Result:
if not self.evaluated:
self._result = self._func(*self._evaluate_args(), **self._evaluate_kwargs())
self.evaluated = True
return self._result
@property
def e(self) -> Result:
return self.evaluate()
__all__ = (
"Lazy",
)

View file

View file

@ -0,0 +1,35 @@
import pytest
from royalnet.lazy import Lazy
def test_single_eval_no_args():
lazy = Lazy(lambda: 1)
assert not lazy.evaluated
assert lazy._result is None
result = lazy.evaluate()
assert result == 1
assert lazy.evaluated
assert lazy._result == 1
def test_single_eval_with_args():
lazy = Lazy(lambda a, b: a + b, 10, 10)
result = lazy.evaluate()
assert result == 20
assert lazy.evaluated
assert lazy._result == 20
def test_chained_eval():
twenty = Lazy(lambda a, b: a + b, 10, 10)
assert not twenty.evaluated
assert twenty._result is None
twentyfive = Lazy(lambda a, b: a + b, twenty, 5)
assert not twentyfive.evaluated
assert twentyfive._result is None
result = twentyfive.evaluate()
assert result == 25
assert twenty.evaluated
assert twenty._result == 20
assert twentyfive.evaluated
assert twentyfive._result == 25