f“{expr=}”是一个新的fstring表达式(请参见训练大括号前的等号)?从哪个版本的python开始?

2024-09-28 17:16:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我收到了一个python笔记本,其中充满了像f"{expr=}"这样的表达式,它们在我的环境中会产生错误消息:

var=7

print(f"{var=}")

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

我怀疑/期望它实际上可能是f"expr={expr}"的一种新语法,即如下print语句:

print(f"var={var}")

var=7

事实上,我经常使用类似于后者的表达式来进行调试,如果能有一个简写就好了

这是比我的python(3.7.6)更高的版本吗?或者它是fstring模块的定制? 在web或SE上搜索它并没有什么效果

如果它不是一个标准功能,我如何才能让它工作


Tags: 消息环境表达式var错误line语法笔记本
2条回答

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

这个特性在Python issue 36817中讨论过,并在Python 3.8中发布

相关问题 更多 >