A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2018-February/152125.html below:

[Python-Dev] Dataclasses and correct hashability

[Python-Dev] Dataclasses and correct hashabilityTerry Reedy tjreedy at udel.edu
Mon Feb 5 04:25:28 EST 2018
On 2/5/2018 2:28 AM, Glenn Linderman 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.

I believe there is no internal difference.  An object is immutable if 
there is not way to mutate it with Python code that not poke into 
internals, such as one can do with ctypes or 3rd party extensions. 
Numbers and strings have no mutation methods, including no .__init__.

A tuple is a fixed sequence of objects and has no .__init__.  But if any 
object in a tuple is mutable, then the tuple is.  But the tuple does not 
know its status, and there is no 'is_mutable' function. However, 
tuple.__hash__ calls the .__hash__ method of each object and if that is 
missing for one, tuple.__hash raises.

 >>> hash((1, 'a', []))
Traceback (most recent call last):
   File "<pyshell#0>", line 1, in <module>
     hash((1, 'a', []))
TypeError: unhashable type: 'list'

The built-in immutable objects are mutated from their initial blank 
values in the C code of their .__new__ methods.  So they are only 
'immutable' once constructed.  Guido pointed out that users constructing 
objects in Python code might reasonably do so other than only with 
.__new__, but still want to treat the object as immutable once constructed.

In Lisp, for instance, lists are actually trees.  To be immutable, they 
can only be singly linked and must be constructed from leaf nodes to the 
root (or head).  Python programmers should be able to link in both 
directions and start from the root, and still treat the result as frozen 
and hashable.

> 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?

Something like this has been proposed, at least for dicts, and rejected.

-- 
Terry Jan Reedy

More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4