在Python(3.11)中,为什么在f字符串中使用赋值表达式("walrus运算符")时需要用括号括起来?
例如:
#!/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)))
上面包含print(f"{_numel := v.numel()}")
的代码块不会进行解析.
那么解析/AST创建要求这样做呢?