On Wed, May 26, 2021 at 9:20 PM Richard Damon <[email protected]> wrote:
>
> On 5/26/21 5:55 AM, Shreyan Avigyan wrote:
> > Reply to Steven -
> >
> > Literals mean 10 or 20. Can you assign something to literal? No. But you 
> > can assign something to a variable to point to another value. That's why I 
> > said constants should behave like literals. Point is constants are names 
> > bind to a value. We can change the value but not the name to point to a 
> > different value. Simply think "const type *pointer" not "type *pointer 
> > const".
> >
> > And by debugging I meant it would immediately be detectable if someone 
> > tries to change the constant or not. (Not a good argument in constant's 
> > favor though)
>
> I think the biggest problem is that basically, by definition, to
> actually enforce this requires a attribute lookup on EVERY rebinding or
> mutating operation.
>
> One stated goal was that
>
> constant mylist = [1, 2, 3]
>
> was to generate an error if you do
>
> mylist.append(4)
>
> but that also means we need to catch
>
> yourlist = mylist
>
> yourlist.append(4)
>
> and since that binding could happen on a cross module function call,
> every mutating operation needs a run-time check to see if this object
> has been bound to a constant.
>

That's basically going to be impossible, especially since the object
could reference OTHER objects which could change, too. Plus, it should
be perfectly valid to say mylist.index(4) even if you can't do
mylist.append(4), so you can't just guard against method calls.

Enforcing immutability externally is basically impossible. Don't even
bother trying.

A more viable proposal might be "this name represents this literal",
and should always be interpreted identically to that literal. So if
you have that constant declaration, then every use of mylist is
exactly equivalent to writing [1, 2, 3] at that exact point in the
code (constructing a new list every time). That'd be well-defined and
plausibly behaved, while still strongly recommending that immutables
be used (since the compiler can constant-fold
ints/floats/tuples/strings). The value would be that if you *edit* the
constant (not rebind it, actually edit the source code), it would
change in all places. I don't think it's of great value and I'm not
recommending it, but it would at least be a sane and plausible
proposal, without logical contradictions.

ChrisA
_______________________________________________
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/X7Z2QIWIXCDDUHKMZSTORO7RDRGDPTKJ/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to