Skip to content

Commit

Permalink
Factor "unwrapped evaluation" of declarations.
Browse files Browse the repository at this point in the history
Some declarations are merely wrapping another one (`Maybe`, etc.).
Add a helper to simplify unwrapping-and-evaluating said declaration.
  • Loading branch information
rbarrois authored and francoisfreitag committed Jun 22, 2023
1 parent 53b34d5 commit d498bcd
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 additions & 10 deletions factory/declarations.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,21 @@ def unroll_context(self, instance, step, context):
subfactory = factory.base.DictFactory
return step.recurse(subfactory, full_context, force_sequence=step.sequence)

def _unwrap_evaluate_pre(self, wrapped, *, instance, step, overrides):
"""Evaluate a wrapped pre-declaration.
This is especially useful for declarations wrapping another one,
e.g. Maybe or Transformer.
"""
if isinstance(wrapped, BaseDeclaration):
return wrapped.evaluate_pre(
instance=instance,
step=step,
overrides=overrides,
)
else:
return wrapped

def evaluate_pre(self, instance, step, overrides):
context = self.unroll_context(instance, step, overrides)
return self.evaluate(instance, step, context)
Expand Down Expand Up @@ -492,16 +507,14 @@ def evaluate_post(self, instance, step, overrides):
def evaluate_pre(self, instance, step, overrides):
choice = self.decider.evaluate(instance=instance, step=step, extra={})
target = self.yes if choice else self.no

if isinstance(target, BaseDeclaration):
return target.evaluate_pre(
instance=instance,
step=step,
overrides=overrides,
)
else:
# Flat value (can't be POST_INSTANTIATION, checked in __init__)
return target
# The value can't be POST_INSTANTIATION, checked in __init__;
# evaluate it as `evaluate_pre`
return self._unwrap_evaluate_pre(
target,
instance=instance,
step=step,
overrides=overrides,
)

def __repr__(self):
return f'Maybe({self.decider!r}, yes={self.yes!r}, no={self.no!r})'
Expand Down

0 comments on commit d498bcd

Please sign in to comment.