问题
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