不能使用带下标的赋值表达式 [英] Cannot use assignment expressions with subscript

查看:33
本文介绍了不能使用带下标的赋值表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

为什么 Python 禁止使用 walrus 运算符?

Why Python forbids this use of walrus operator?

推荐答案

因为,正如替代名称(命名表达式)所暗示的,海象操作员的左侧是NAME.因此,根据定义,您的问题中提到的此类表达式以及例如函数调用不允许以这种形式分配.

Because, as the alternative name (named expressions) suggests, the left hand side of the walrus operator is to be a NAME. Therefore, by definition such expressions as noted in your question as well as, for instance, function calls are not allowed to be assigned in this form.

文档还规定:

支持除单个NAME之外的单个分配目标

Single assignment targets other than a single NAME are not supported

为了进一步说明这一论点,可以注意到 cPython 明确地检查 如果表达式是 Name_kind:

To further this argument, one can notice that cPython explicitly checks if the expression is Name_kind:

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;
}

这篇关于不能使用带下标的赋值表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆