On Wed, May 26, 2021 at 12:31:07PM -0000, Shreyan Avigyan wrote:
> Reply to Paul Moore:
>
> if some_condition:
> constant a = 1
> else:
> a = 2
> a = 3
>
> Yes this is allowed. This is runtime.
Do you have any suggestions for how this should be implemented, how the
interpreter will know at runtime whether or not the name `a` is a
constant?
> for i in range(10):
> constant a = []
>
> Not sure. Though it's preferable to be runtime. Preferable is "not allowed".
That is equivalent to:
constant a = []
constant a = []
constant a = []
# seven more times
If you can't rebind constants, then that better be disallowed. Otherwise
you have rebound the constant `a` nine times: initialised it to one list
on the first loop, and then the next nine loops you bind the same name
to nine different lists.
> And lists are also literals.
Lists are not literals. The documentation calls them *displays*. You
won't find lists under "literals":
https://docs.python.org/3/reference/expressions.html#literals
but you will find them here:
https://docs.python.org/3/reference/expressions.html#list-displays
I admit that I too often wrongly refer to expressions like `[1, 2]` as a
list literal, but that language is not technically correct for Python.
> Any Python Object that is not assigned to a variable is a literal.
That's incorrect. When I write the expression:
print(a*x + b)
the object returned by `a*x + b` is not assigned to anything, but it's
not a literal.
> Python claims that itself. A preview -
>
> [10] = [2]
> SyntaxError: Can't assign to literal here.
You are misinterpreting the error. If you look at the pointer in the
syntax error, it points at the 10, not the list:
>>> [10] = [2]
File "<stdin>", line 1
[10] = [2]
^
SyntaxError: cannot assign to literal
That statement is doing sequence unpacking: it unpacks the list [2], and
the target list [10], and tries to assign 10 = 2 which is forbidden
because 10 is a literal, *not* because `[10]` is a literal. (It isn't.)
You can see a better example here:
>>> [a, b, c, 10, d, e] = range(6)
File "<stdin>", line 1
[a, b, c, 10, d, e] = range(6)
^
SyntaxError: cannot assign to literal
--
Steve
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/K47EGJ63HIOHP7DDQWDP3FXX42L5ENVE/
Code of Conduct: http://python.org/psf/codeofconduct/