[issue31263] Assigning to subscript/slice of literal is permitted

Isaac Elliott report at bugs.python.org
Wed Aug 23 18:21:33 EDT 2017


Isaac Elliott added the comment:

Yes I would disallow a script such as
`a = [0]; [5, a][1][:] = [3]` (note: your example of just `[5, a][1][:] = [3]` does not run, so I assumed it must be used in a situation like this)

Evaluating the target of an assignment is unnecessary, we can syntactically determine whether some left hand side can be assigned to:

* Identifiers are assignable (`a = 2`)
* Attribute accesses are assignable, provided that the left of the dot is assignable (`a.foo = 2`, `a.b.c.foo`, etc)
* Subscripts are assignable, provided that the outer expression is assignable (`a[1] = 2`, `a.foo[b] = 2`, `a[1][2][3] = 2`, `a.b[1].c[2] = 2`)
* Lists are assignable, provided that all their elements are assignable (`[a,b,c] = [1,2,3]`)
* Expression lists/tuples are assignable, provided that all their elements are assignable (`a, b = (1, 2)`, `(a,b,c) = (1,2,3)`)
* Unpackings are assignable, provided that their argument is assignable (`*a, = [1,2,3]`, `a, *b = [1,2,3]`)
* Slices are assignable, provided that the outer expression is assignable (`a[:] = [1,2,3]`, `a.foo[1:2] = [1]`
* Everything else is not assignable (did I forget anything?)

This can definitely be encoded as a context-free grammar, although I don't know if it will present conflicts in the parser generator.

I do think it's worth it. Python is one of the most widely used programming languages, and it's our responsibility to ensure it behaves correctly.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue31263>
_______________________________________


More information about the Python-bugs-list mailing list