I want to use some classes as dictionary keys.
Python is not objecting,
but I'm not sure how to think about
whether this could be dangerous.
I'm inclined to guess it will be hashed by id
and this is OK.
Thanks for any insights,
Alan Isaac
> Are user defined classes hashable?
> (The classes; *not* the instances!)
>
> I want to use some classes as dictionary keys.
> Python is not objecting,
> but I'm not sure how to think about
> whether this could be dangerous.
> I'm inclined to guess it will be hashed by id
> and this is OK.
You can check for yourself:
In [1]: class Foo(object):
...: pass
...:
In [2]: foo = Foo()
In [3]: hash
hash
In [3]: hash(foo)
Out[3]: 15294992
In [4]: id(foo)
Out[4]: 15294992
So yes, by default, user-defined classes are hashable, by id. You can
override this behaviour by defining the __hash__ special method on
your object.
HTH,
--
Nicolas Dandrimont
On 7/19/2009 10:07 AM Nicolas Dandrimont apparently wrote:
> You can check for yourself:
> In [1]: class Foo(object):
> ...: pass
> ...:
> In [2]: foo = Foo()
> In [3]: hash(foo)
> Out[3]: 15294992
> In [4]: id(foo)
> Out[4]: 15294992
Again, my question is about the class not its instances,
but still, checking as you suggest gives the same answer.
Thanks,
Alan
That's what I get for answering before my coffee!
Cheers,
--
Nicolas Dandrimont
"Linux poses a real challenge for those with a taste for late-night
hacking (and/or conversations with God)."
(By Matt Welsh)
Regardless, Nicolas's example can be applied to the class too:
>>> class Foo(object):
pass
>>> hash(Foo)
11443104
>>> id(Foo)
11443104
class objects are just objects of type 'type'.
Not quite. They certainly default that way, but changing the metaclass
changes a class's type::
class M(type):
pass
class C(object):
pass
class C2(object):
__metaclass__ = M
print type(C)
print type(C2)
--
Aahz (aa...@pythoncraft.com) <*> http://www.pythoncraft.com/
"The volume of a pizza of thickness 'a' and radius 'z' is
given by pi*z*z*a"
Well, okay, you got me there. But the OP wasn't asking about classes
with different metaclasses. And besides, type(type(C2)) is still
type ;)