On 2/19/2018 7:02 PM, Guido van Rossum wrote:
But how?
On Mon, Feb 19, 2018 at 5:06 PM, Chris Barker - NOAA Federal
<chris.bar...@noaa.gov <mailto:chris.bar...@noaa.gov>> wrote:
... maybe it would be helpful to be able to
freeze an instance after creation for multiple use-cases?
And there's the crux of the issue... if the creator of Python can't
figure out how to make mutable objects immutable by fiat after creation,
then it is unlikely anyone else can!
Yet it seems there are use cases for that sort of ability.
Is it not possible to strip an object of its operations that mutate it?
Probably it is, but, in doing so, it might strip the whole class of the
operations that mutate it, rendering it impossible to the create
additional mutable instances of the same class. In another message,
Guido suggests that the solution of having a flag for each object, that
presumably would be checked by each mutation operation, is not a
wonderful idea:
On 2/18/2018 6:30 PM, Guido van Rossum wrote:
The underlying issue here is that we don't want an extra state flag in
the object to indicate "this object is currently [im]mutable". Using
__class__ assignment to signal this is clever way to add this state,
though not without risks.
My only suggestion here is to add a new type of class to the language:
one that would effectively be two nearly identical classes under the
covers, having all the same interfaces and internal data structures.
Both internal classes would be subclasses of the new class, for is-a
purposes. But they would be defined in such a way (if there is such a
way) as to minimize the risks referred to just above (I don't know what
those risks are), so that mutable instances could become immutable via
__class__ assignment.
So just to play with this a bit in high-level syntax:
freezable_class Foo: # or maybe class Foo( freezable ):
int bar;
All instances of Foo would first be created as __mutable__Foo. Both
__mutable__Foo and __immutable__Foo would be instance_of( Foo ).
Foo xyz
xyz.bar = 17 # works fine
xyz.bar += 1 # works fine
if xyz.bar == 18:
pass # True
if instance_of( xyz, Foo ):
pass # True
if instance_of( xyz, __mutable__Foo ):
pass # True
Foo would have an implicitly defined method (or defined on the parent
freezable class) that would convert a class from __mutable__Foo to
__immutable__Foo. There would be no reverse conversion.
xyz.__immutable__() # under the covers, assigns xyz.__class__ to
__immutable__Foo
Mutating methods applied to __immutable__Foo instances would cause
exceptions, because they wouldn't exist for the __immutable__Foo subclass.
if xyz.bar == 18:
pass # True
if instance_of( xyz, __mutable__Foo ):
pass # False
else:
print("Can't change it any more.")
xyz.bar = 19 # throws: xyz is now immutable
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com