How to evaluate a variable as an f-string?

f-string, python, python-3.6, python-3.x, string-interpolation

Solution

Even with a trusted user, using `eval` should only be a very last resort.

If you are willing to sacrifice flexibility of your syntax for a bit more security and control, then you could use `str.format` and provide it your whole scope.

This will disallow evaluation of expressions, but single variables will be formated into the output.

Code

x = 3
y = 'foo'

s = input('> ')
print(s.format(**vars()))

Example

> {x} and {y}
3 and foo

Problem

I would like to have a mechanism which evaluates an f-string where the contents to be evaluated are provided inside a variable. For example, ``` x=7 s='{x+x}' fstr_eval(s) ``` For the usage case I have in mind, the string `s` may arise from user input (where the user is trusted with `eval`). While using `eval` in production is generally very bad practice, there are notable exceptions. For instance, the user may be a Python developer, working on a local machine, who would like to use full Python syntax to develop SQL queries. Note on duplication: There are similar questions here and here. The first question was asked in the limited context of templates. The second question, although very similar to this one, has been marked as a duplicate. Because the context of this question is significantly different from the first, I decided to ask this third question based on the automatically-generated advice following the second question: This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

Original source

Related problems