Skip to content Skip to sidebar Skip to footer

Cannot Use Assignment Expressions With Subscript

if session['dp'] := current_user.avatar : ^ SyntaxError: cannot use assignment expressions with subscript Why Python forbids this use of walrus operator?

Solution 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) {
    constchar *expr_name = get_expr_name(target);
    if (expr_name != NULL) {
        ast_error(c, n, "cannot use assignment expressions with %s", expr_name);
    }
    returnNULL;
}

Solution 2:

There is some justification for the decision to disallow more complex assignments in assignment expressions given on the python-dev mailing list.

In particular, from 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

and from Guido himself:

Also nobody had a use case.

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

That's probably as close to an explanation as is possible. Presumably if there's demand the feature may be expanded in some future version.

Post a Comment for "Cannot Use Assignment Expressions With Subscript"