=(等于)在表达式大括号内的 f 字符串中有什么作用?

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

众所周知,Python f 字符串中 {} 的用法是执行代码片段并以 string 格式给出结果(一些教程 此处).但是,表达式末尾的'='是什么意思?

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

这其实是一个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.

本质上,它有助于打印调试的频繁用例,因此,我们通常必须编写:

f"some_var={some_var}"

我们现在可以写:

f"{some_var=}"

因此,作为演示,使用全新的 Python 3.8.0 REPL:

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

如前所述here:

Equals signs are now allowed inside f-strings starting with Python 3.8. This lets you quickly evaluate an expression while outputting the expression that was evaluated. It's very handy for debugging.:

表示会运行执行f串大括号中的代码,并在最后加上等号

所以它实际上意味着:

"something={executed something}"

从 Python 3.8 开始,f-strings 支持 "self-documenting expressions",主要用于打印调试。来自 the docs:

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. For example:

user = 'eric_idle'
member_since = date(1975, 7, 31)
f'{user=} {member_since=}'
"user='eric_idle' member_since=datetime.date(1975, 7, 31)"

The usual f-string format specifiers allow more control over how the result of the expression is displayed:

>>> delta = date.today() - member_since
>>> f'{user=!s}  {delta.days=:,d}'
'user=eric_idle  delta.days=16,075'

The = specifier will display the whole expression so that calculations can be shown:

>>> print(f'{theta=}  {cos(radians(theta))=:.3f}')
theta=30  cos(radians(theta))=0.866

这是在 python 3.8 中引入的。它有助于在编写代码时减少很多 f'expr = {expr}。您可以在 What's new in Python 3.8.

查看文档

Raymond Hettinger in his tweet 展示了一个很好的例子:

>>> from math import radians, sin
>>> for angle in range(360):
        print(f'{angle=}\N{degree sign} {(theta:=radians(angle))=:.3f}')
angle=0° (theta:=radians(angle))=0.000
angle=1° (theta:=radians(angle))=0.017
angle=2° (theta:=radians(angle))=0.035
angle=3° (theta:=radians(angle))=0.052
angle=4° (theta:=radians(angle))=0.070
angle=5° (theta:=radians(angle))=0.087
angle=6° (theta:=radians(angle))=0.105
angle=7° (theta:=radians(angle))=0.122
angle=8° (theta:=radians(angle))=0.140
angle=9° (theta:=radians(angle))=0.157
angle=10° (theta:=radians(angle))=0.175
...

您还可以查看 this 以了解为什么首先提出此建议的基本想法。