Skip to content

Instantly share code, notes, and snippets.

@dah33
Last active October 8, 2023 23:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dah33/e18e71a81d1a0aaf59658269ada963b3 to your computer and use it in GitHub Desktop.
Save dah33/e18e71a81d1a0aaf59658269ada963b3 to your computer and use it in GitHub Desktop.
How to make a function closure in Jinja / dbt
{# Save these macros in your dbt project /macros folder: #}
{% macro enclose(fn, env) %}
{% set closure = namespace(fn=fn, env=env) %}
{% do return(closure) %}
{% endmacro %}
{% macro call1(closure, x1) %}
{% do return(closure.fn(x1, closure.env)) %}
{% endmacro %}
{% macro call2(closure, x1, x2) %}
{% do return(closure.fn(x1, x2, closure.env)) %}
{% endmacro %}
{% macro power(x, kwargs) %}
{% do return(x**kwargs.exponent) %}
{% endmacro %}
{# Example, within a dbt model: #}
{% set square = enclose(power, dict(exponent=2)) %}
{{ call1(square, 8) }}{# = 8**2 = 64 #}
@dah33
Copy link
Author

dah33 commented Oct 8, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment