In Python (3.11) why does the use of an assignment expression (the "walrus operator") require wrapping in parentheses when used inside an f-string?
For example:
#!/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)))
The code block above with print(f"{_numel := v.numel()}")
instead does not parse.
What about the parsing / AST creation mandates this?
(...)
, a more complete expression. For what it's worth, assigning a variable inside an f-string is pretty dirty and should be avoided.:
could be used inside{}
in an f-string? (Something innate to the formatting system, not to do with the expression.)