Skip to content
Advertisement

What does = (equal) do in f-strings inside the expression curly brackets?

The usage of {} in Python f-strings is well known to execute pieces of code and give the result in string format (some tutorials here). However, what does the ‘=‘ at the end of the expression mean?

log_file = open("log_aug_19.txt", "w") 
console_error = '...stuff...'           # the real code generates it with regex
log_file.write(f'{console_error=}')

Advertisement

Answer

This is actually a brand-new feature as of Python 3.8.

Added an = specifier to f-strings. An f-string such as f'{expr=}' will expand to the text of the expression, an equal sign, then the representation of the evaluated expression.

Essentially, it facilitates the frequent use-case of print-debugging, so, whereas we would normally have to write:

f"some_var={some_var}"

we can now write:

f"{some_var=}"

So, as a demonstration, using a shiny-new Python 3.8.0 REPL:

>>> print(f"{foo=}")
foo=42
>>>
Advertisement