Evaluation of variable as f-string

Chris Angelico rosuav at gmail.com
Mon Jan 23 13:02:56 EST 2023


On Tue, 24 Jan 2023 at 04:56, Johannes Bauer <dfnsonfsduifb at gmx.de> wrote:
>
> Hi there,
>
> is there an easy way to evaluate a string stored in a variable as if it
> were an f-string at runtime?
>
> ...
>
> This is supposedly for security reasons. However, when trying to emulate
> this behavior that I wanted (and know the security implications of), my
> solutions will tend to be less secure. Here is what I have been thinking
> about:

If you really want the full power of an f-string, then you're asking
for the full power of eval(), and that means all the security
implications thereof, not to mention the difficulties of namespacing.
Have you considered using the vanilla format() method instead?

But if you really REALLY know what you're doing, just use eval()
directly. I don't really see what you'd gain from an f-string. At very
least, work with a well-defined namespace and eval whatever you need
in that context.

Maybe, rather than asking for a way to treat a string as code, ask for
what you ACTUALLY need, and we can help?

ChrisA


More information about the Python-list mailing list