无法将赋值表达式与下标一起使用

2024-06-16 10:05:30 发布

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

if session['dp'] := current_user.avatar :
    ^ SyntaxError: cannot use assignment expressions with subscript

为什么Python禁止使用walrus操作符


Tags: ifusesessionwithcurrentexpressionsdpassignment
2条回答

在python-dev邮件列表中给出的赋值表达式中不允许更复杂的赋值,这是有道理的

特别是Chris Angelico:

Assignment to arbitrary targets would also mean permitting iterable unpacking, which is not desired ("x, y := 3, 4"??), and there weren't enough use-cases for attribute/item assignment to justify creating a rule of "you can assign to any single target, but can't unpack". In the future, if such use-cases are found, the grammar can be expanded.

https://mail.python.org/pipermail/python-dev/2018-July/154628.html

来自圭多本人:

Also nobody had a use case.

https://mail.python.org/pipermail/python-dev/2018-July/154631.html

这可能是一个尽可能接近的解释。据推测,如果有需求,该功能可能会在未来的某个版本中扩展

因为,正如替代名称(命名表达式)所示,the left hand side of the walrus operator is to be a ^{}。因此,根据定义,您的问题中提到的表达式以及(例如)函数调用不允许在此表单中分配

文件还规定:

Single assignment targets other than a single NAME are not supported

为了进一步说明这个论点,可以注意到,如果表达式为^{,则cPython显式地checks

if (target->kind != Name_kind) {
    const char *expr_name = get_expr_name(target);
    if (expr_name != NULL) {
        ast_error(c, n, "cannot use assignment expressions with %s", expr_name);
    }
    return NULL;
}

相关问题 更多 >