How to use self-docummenting equals (debugging) specifier with str.format()?
Asked Answered
C

0

0

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.
Chiachiack answered 27/7, 2020 at 18:24 Comment(2)
To be more specific, is there a way different than eval()?Chiachiack
This is something that is specific to f-strings as far as I am awareAfterworld

© 2022 - 2024 — McMap. All rights reserved.