[Python-ideas] Support other dict types for type.__dict__
Jim Jewett
jimjjewett at gmail.com
Mon Feb 27 21:39:37 CET 2012
On Sat, Feb 25, 2012 at 6:32 PM, Masklinn <masklinn at masklinn.net> wrote:
> On 2012-02-26, at 00:05 , Steven D'Aprano wrote:
>> - Immutable types can be used as keys in dicts.
Not always; for example, you can't use a tuple of lists, even though
the tuple itself is immutable.
> *technically*, you can use mutable types as dict keys if you define
> their __hash__ no? That is of course a bad idea when the instances
> are *expected* to be modified, but it should "work".
Not even a bad idea, if you define the hash carefully. (Similar to
java final.)
Once hash(obj) returns something other than -1, it should return that
same value forever. Attributes which do not contribute to the hash
can certainly still change.
That said, I would be nervous about changes to attributes that
contribute to __eq__, just because third party code may be so
surprised.
>>> class Str(str): pass
>>> a=Str("a")
>>> a.x=5
>>> a == "a"
True
>>> "x" in dir("a")
False
>>> "x" in dir(a)
True
-jJ
More information about the Python-ideas
mailing list