Evaluation of variable as f-string
Peter J. Holzer
hjp-python at hjp.at
Sat Jan 28 08:41:13 EST 2023
On 2023-01-27 21:43:09 +0100, Johannes Bauer wrote:
> x = { "y": "z" }
> s = "-> {x['y']}"
> print(s.format(x = x))
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> KeyError: "'y'"
>
> This. Does. Not. Work.
>
> I want to pass a single variable as a dictionary and access its members
> inside the expression.
You can do that (see other responses), but you can't have arbitrary
Python expressions inside a format string.
It works with f-strings because f-strings are a compiler construct. The
f-string never exists at run-time. Instead the compiler transforms
f"-> {x['y']}"
into the equivalent of
"-> " + format_value(x["y"]) + ""
So either you need to pass it to the Python compiler (via eval), or you
need to implement enough of a Python parser/interpreter to cover the
cases you are interested in. The latter might be an interesting
exercise, but I would suggest looking at existing template engines like
Jinja2 for production purposes.
hp
--
_ | Peter J. Holzer | Story must make more sense than reality.
|_|_) | |
| | | hjp at hjp.at | -- Charles Stross, "Creative writing
__/ | http://www.hjp.at/ | challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20230128/61e336ae/attachment.sig>
More information about the Python-list
mailing list