Re: [Tutor] unhashable objects (unrelated to previous topic)
Orri Ganel wrote: Thanks to Jeff and John Fouhy . . . However, my question now is: can I treat Nodes sometimes the same and sometimes not? I want to treat Nodes whose cargo is the same the same everywhere *except* in a dictionary, because I want the user to be able to use LinkedList in a broader way than sets allow . . . In order to do this, I need my __hash__() method to treat Nodes differently than the rich comparison methods do. Is this a Bad Idea(tm) ? The problem is, if you have two Nodes a and b where a == b, you will expect that for any dictionary d[a] == d[b]. If Node.__eq__() has different semantics than Node.__hash__() this expectation will not be correct. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unhashable objects (unrelated to previous topic)
Thanks to Jeff and John Fouhy . . . However, my question now is: can I treat Nodes sometimes the same and sometimes not? I want to treat Nodes whose cargo is the same the same everywhere *except* in a dictionary, because I want the user to be able to use LinkedList in a broader way than sets allow . . . In order to do this, I need my __hash__() method to treat Nodes differently than the rich comparison methods do. Is this a Bad Idea(tm) ? -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unhashable objects (unrelated to previous topic)
On Sun, 27 Mar 2005 18:08:41 -0500, Orri Ganel <[EMAIL PROTECTED]> wrote: > Hello all, > > I am attempting to implement a LinkedList in Python, and in doing so, > have created a Node class which represents the elements of the > LinkedList. However, since these Nodes have custom-defined __lt__(), > __gt__(), __le__(), __ge__(), __eq__(), and __ne__() methods, they > are, for some reason, unhashable. When I comment out these methods, > Python makes no complaint. But when they are present, 'TypeError: > unhashable instance' is raised when attempting to use a Node as a key > in a dictionary. When you don't define __eq__(), Python will use an object's ID as its hash value. However, the standard usage of hashes implies that objects which compare as equal should hash identically. This means that objects which define __eq__() and which are intended to be hashed need to define a __hash__() method. Be very careful if you're doing this with mutable objects, though -- you need to either hash by object identity or by object equality, and for mutable objects either choice will leave you breaking an implied promise. (Either a single object will not hash the same at different points in its life, or objects which are equal will not hash identically.) Jeff Shannon ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor