Cannot use assignment expressions with subscript

こ雲淡風輕ζ 提交于 2020-05-23 13:12:06

问题


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

Why Python forbids this use of walrus operator?


回答1:


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.

The documentation also specifies:

Single assignment targets other than a single NAME are not supported

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


来源:https://stackoverflow.com/questions/60908298/cannot-use-assignment-expressions-with-subscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!