Skip to content

Commit

Permalink
Use plugin architecture for builtin functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Paul Prescod committed May 1, 2020
1 parent b79da29 commit 214444e
Show file tree
Hide file tree
Showing 4 changed files with 194 additions and 183 deletions.
21 changes: 10 additions & 11 deletions snowfakery/data_generator_runtime.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from collections import defaultdict
from functools import partial
from datetime import date
from contextlib import contextmanager

Expand All @@ -11,7 +10,7 @@

from .utils.template_utils import FakerTemplateLibrary

from .template_funcs import template_funcs
from .template_funcs import StandardFuncs
from .data_gen_exceptions import DataGenSyntaxError, DataGenNameError
import snowfakery # noqa

Expand Down Expand Up @@ -217,6 +216,14 @@ def __init__(
self.faker_template_library = FakerTemplateLibrary(faker_providers)
self.globals = globals or Globals()

# inject context into the standard functions
standard_funcs_obj = StandardFuncs(self).custom_functions()
self.standard_funcs = {
name: getattr(standard_funcs_obj, name)
for name in dir(standard_funcs_obj)
if not name.startswith("_") and name != "context"
}


class RuntimeContext:
"""Local "stack frame" type object. RuntimeContexts live on the Python stack.
Expand Down Expand Up @@ -328,18 +335,10 @@ def simple_field_vars(self):
**interpreter.plugin_function_libraries,
}

# todo: should be replaced with the plugin architecture
def field_funcs(self):
"Injects context into functions from template_funcs module."

def curry(func):
rc = partial(func, self.runtime_context)
if hasattr(func, "lazy"):
rc.lazy = func.lazy
return rc

funcs = {name: curry(func) for name, func in template_funcs.items()}
return {**funcs}
return self.runtime_context.interpreter.standard_funcs

def executable_blocks(self):
"Return mapping of functions that can be used in YAML block functions"
Expand Down
12 changes: 12 additions & 0 deletions snowfakery/plugins.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from typing import Any, Callable


class SnowfakeryPlugin:
"""Base class for all plugins.
Expand Down Expand Up @@ -60,3 +63,12 @@ def context_vars(self):
return self.interpreter.current_context.context_vars(
self.plugin.__class__.__name__
)

def evaluate(self, field_definition):
return field_definition.render(self.interpreter.current_context)


def lazy(func: Any) -> Callable:
"""A lazy function is one that expects its arguments to be unparsed"""
func.lazy = True
return func
Loading

0 comments on commit 214444e

Please sign in to comment.