Search code examples
pythondebuggingf-string

is f"{expr=}" a new f-string expression (see equal sign before training brace)? from which version of python on?


I have received a python notebook that is full of expressions like f"{expr=}" that in my environment produce error messages:

var=7

print(f"{var=}")

  File "<fstring>", line 1
    (var=)
        ^
SyntaxError: invalid syntax

I suspect/expect that it could be in fact a new syntax for f"expr={expr}", i.e. as in the following print statement:

print(f"var={var}")

var=7

In fact I often use expressions like the latter for debug, and it would be nice to have a shorthand for it.

Is that a higher version of python than mine (3.7.6)? Or is it a customization of the fstring module? Searching for it on the web or in SE was not productive.

And if it is not a standard feature, how can I get it to work?


Solution

  • Answer - Python Version 3.8

    f-strings simplified a lot of places where str.format and % style formatting. There was still a place where you want to print a value of the variable or expression and also add some context with the string like variable name or some arbitrary name so that when you have many statements you can differentiate between the printed values. So using variable name followed by value is more common format of print style debugging. Blockquote This caused users to write f"name = {name}" and can get unwieldy when variable names are long like filtered_data_from_third_party would be written as f"filtered_data_from_third_party = {filtered_data_from_third_party}". In those cases we resort to shorter names we understand easily at the context like f"filtered data {filtered_data_from_third_pary}". f-strings also support format specifiers so you can write f"{name!r}" which is same as f"{repr(name)}".

    Given the above boilerplate an idea was posted in python-ideas around a format specifier where you can use it and the f-string would expand like a macro into <variable_name> = <value_of_variable>. Initially !d was chosen so f"{name!d}" would expand to f"name={repr(name)}". This was initially implemented in bpo36774. After discussion !d was changed to use = with input from Guido and other core devs since there could be usecases served by !d in the future and to reserve alphabetical names in format-string for other uses. So this was changed to use = as the notation for this feature in bpo36817. An overview of it’s usage is as below with various features available.

    Read more here