Python 3.8 introduced =
specifier in f-strings (see this issue and pull request).
It allows to quickly represent both the value and the name of the variable:
from math import pi as π
f'{π=}'
# 'π=3.141592653589793'
I would like to use this feature on a pre-defined string with str.format()
:
'{π=}'.format(π=π)
However, it raises an exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'π='
Is there a way to make it work (e.g. with a special dunder method)?
Why it may be useful?
- one could have a programmatic template for multiple values of the same variable (in a loop)
- in contrasts, f-strings have to be hardcoded; think about internationalization
- one could reference constants defined in a module in its docstring (
module.__doc__.format(**vars(module)
);- workaround: define an f-string variable at the end of the module, overwrite the
module.__doc__
at runtime.
- workaround: define an f-string variable at the end of the module, overwrite the
eval()
? – Chiachiack