相关疑难解决方法(0)

为什么 f 字符串需要在赋值表达式两边加上括号?

在 Python (3.11) 中,为什么在 f 字符串内使用赋值表达式(“海象运算符”)时需要用括号括起来?

例如:

#!/usr/bin/env python

from pathlib import Path

import torch


DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")

ckpt_dir = Path("/home/path/to/checkpoints")

_ckpt = next(ckpt_dir.iterdir())
print(_ckpt)
sdict = torch.load(_ckpt, map_location=DEVICE)

model_dict = sdict["state_dict"]

for k, v in model_dict.items():
    print(k)
    print(type(v))
    print(_shape := v.size())
    print(f"{(_numel := v.numel())}")
    print(_numel == torch.prod(torch.tensor(_shape)))
Run Code Online (Sandbox Code Playgroud)

上面的代码块 withprint(f"{_numel := v.numel()}")相反不会解析。

解析/AST 创建是否要求这样做?

python f-string python-assignment-expression

15
推荐指数
2
解决办法
1650
查看次数