Y
Y
YelKa2022-04-16 10:43:19
Jinja
YelKa, 2022-04-16 10:43:19

How to create a variable from a string?

We need to create some similar functions, but different in name and slightly in content in Jinja. Is it possible to create function names from strings using a loop, iterating over an array with strings?
Something like exec(str)in python.

for i in ["pow2", "pow3", "pow4"]:
    exec(f"{i} = lambda x: x ** {i[-1]}")
print(pow2(2), pow2(5))
print(pow3(2), pow3(5))
print(pow4(2), pow4(5))
"""
--> 4 25
--> 8 125
--> 16 625
"""

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2022-04-16
@sergey-gornostaev

It is highly undesirable to do this even in ordinary python code, and even more so in the template engine code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question