On 2/5/2018 12:11 AM, Nathaniel Smith wrote:
On Sun, Feb 4, 2018 at 11:28 PM, Glenn Linderman <v+pyt...@g.nevcal.com> wrote:
This is an interesting use case. I haven't got the internals knowledge to
know just how just different mutable and immutable classes and objects are
under the hood. But this use case makes me wonder if, even at the cost of
some performance that "normal" immutable classes and objects might obtain,
if it would be possible to use the various undisciplined initialization
patterns as desired, followed by as declaration "This OBJECT is now
immutable" which would calculate its HASH value, and prevent future
mutations of the object?
It would be technically possible to support something like
@dataclass(freezable=True)
class Foo:
blah: int
foo = Foo()
# Initially, object is mutable, and hash(foo) raises an error
foo.blah = 1
assertRaises(hash, foo)
# This method is automatically generated for classes with freezable=True
foo.freeze()
# Now object is immutable, and hash(foo) is allowed
assertRaises(foo.__setattr__, "blah", 2)
hash(foo)
I don't know if it's worth the complexity, but I guess it would cover
at least some of the use cases Guido raised.
-n
Thanks, Nathaniel, for confirming that what I was suggesting is not
impossible, even if it turns out to be undesirable for some reason, or
unwanted by anyone else. But I have encountered a subset of the use
cases Guido mentioned, and had to make a 2nd class to gather/hold the
values of the eventual immutable class, before I could make it, because
pieces of the data for the class values were obtained from different
sources at different times. Once all collected, then the immutability
could be obtained, the rest of the processing performed. Thrashes the
allocator pretty well doing it that way, but the job got done.
_______________________________________________
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