Evaluation of variable as f-string

Chris Angelico rosuav at gmail.com
Fri Jan 27 14:18:16 EST 2023


On Sat, 28 Jan 2023 at 05:31, Rob Cliffe via Python-list
<python-list at python.org> wrote:
> On 23/01/2023 18:02, Chris Angelico wrote:
> > Maybe, rather than asking for a way to treat a string as code, ask for
> > what you ACTUALLY need, and we can help?
> >
> > ChrisA
> Fair enough, Chris, but still ISTM that it is reasonable to ask (perhaps
> for a different use-case) whether there is a way of evaluating a string
> at runtime as if it were an f-string.  We encourage people to ask
> questions on this list, even though the answer will not always be what
> they're hoping for.

No, it's not, because that's the "how do I use X to do Y" problem.
Instead, just ask how to do *what you actually need*. If the best way
to do that is to eval an f-string, then someone will suggest that.
But, much much much more likely, the best way to do it would be
something completely different. What, exactly? That's hard to say,
because *we don't know what you actually need*. All you tell us is
what you're attempting to do, which there is *no good way to achieve*.

> I appreciate that the answer may be "No, because it would be a lot of
> work - and increase the maintenance burden - to support a relatively
> rare requirement".

What about: "No, because it's a terrible TERRIBLE idea, requires that
you do things horribly backwards, and we still don't even know what
you're trying to do"?

> Perhaps someone will be inspired to write a function to do it. 😎

See, we don't know what "it" is, so it's hard to write a function
that's any better than the ones we've seen. Using eval() to construct
an f-string and then parse it is TERRIBLE because:

1) It still doesn't work in general, and thus has caveats like "you
can't use this type of quote character"
2) You would have to pass it a dictionary of variables, which also
can't be done with full generality
3) These are the exact same problems, but backwards, that led to
f-strings in the first place
4) eval is extremely slow and horrifically inefficient.

For some reason, str.format() isn't suitable, but *you haven't said
why*, so we have to avoid that in our solutions. So, to come back to
your concern:

> We encourage people to ask
> questions on this list, even though the answer will not always be what
> they're hoping for.

Well, yes. If you asked "how can I do X", hoping the answer would be
"with a runtime-evaluated f-string", then you're quite right - the
answer might not be what you were hoping for. But since you asked "how
can I evaluate a variable as if it were an f-string", the only
possible answer is "you can't, and that's a horrible idea".

Don't ask how to use X to do Y. Ask how to do Y.

ChrisA


More information about the Python-list mailing list