Last active
September 14, 2023 06:23
-
-
Save emmaly/c95cbb8c76e36386c7ef1fa46ce5f2db to your computer and use it in GitHub Desktop.
Jinja2 Type Testing (useful for constrained environments)
This file contains 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
None: | |
- none | |
True: | |
- boolean | |
False: | |
- boolean | |
65535: | |
- number | |
- integer | |
123: | |
- number | |
- integer | |
123.0: | |
- number | |
- float | |
inf: | |
- number | |
- float | |
-inf: | |
- number | |
- float | |
hamburger: | |
- string | |
{'food': 'mochi', 'flavor': 'matcha'}: | |
- dict | |
[1, 'tacos', 3, 'ice cream']: | |
- list | |
(1, 'tacos', 3, 'ice cream'): | |
- tuple |
This file contains 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
{% | |
set test_values = [ | |
none, | |
true, | |
false, | |
0xFFFF, | |
123, | |
123.0, | |
float("inf"), | |
-float("inf"), | |
"hamburger", | |
{"food": "mochi", "flavor": "matcha"}, | |
[1, "tacos", 3, "ice cream"], | |
(1, "tacos", 3, "ice cream"), | |
] | |
%} | |
{% for t in test_values %} | |
{%- set v = namespace(types=[]) -%} | |
{%- if t is none -%} | |
{%- set v.types = v.types + ['none'] -%} | |
{%- endif -%} | |
{%- if t is boolean -%} | |
{%- set v.types = v.types + ['boolean'] -%} | |
{%- endif -%} | |
{%- if t is number and t is not boolean -%} | |
{%- set v.types = v.types + ['number'] -%} | |
{%- endif -%} | |
{%- if t is integer -%} | |
{%- set v.types = v.types + ['integer'] -%} | |
{%- endif -%} | |
{%- if t is float -%} | |
{%- set v.types = v.types + ['float'] -%} | |
{%- endif -%} | |
{%- if t is string -%} | |
{%- set v.types = v.types + ['string'] -%} | |
{%- endif -%} | |
{%- if t is mapping -%} | |
{%- set v.types = v.types + ['dict'] -%} | |
{%- endif -%} | |
{%- if t is sequence and t is not mapping and t is not string and t.pop is undefined -%} | |
{%- set v.types = v.types + ['tuple'] -%} | |
{%- endif -%} | |
{%- if t is sequence and t is not mapping and t is not string and t.pop is not undefined -%} | |
{%- set v.types = v.types + ['list'] -%} | |
{%- endif -%} | |
{{ t ~ ":\n - " ~ (v.types | join("\n - ")) }} | |
{% endfor %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment