are user defined classes hashable?

A

Alan G 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.

Thanks for any insights,
Alan Isaac
 
N

Nicolas Dandrimont

* Alan G Isaac said:
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

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkpjKL0ACgkQacIxuZqlam0cxQCcDbvN8obtDgh/U++fA26kktfT
9mIAn0nXU2PvNvKZZNvgsn26ixkIt4/s
=wJyS
-----END PGP SIGNATURE-----
 
N

Nicolas Dandrimont

* Alan G Isaac said:
Again, my question is about the class not its instances,
but still, checking as you suggest gives the same answer.

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)

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkpjPjMACgkQacIxuZqlam2uFACfT1tdR5n/8nTY7DhOfve/JFE3
C3MAn1VdduhIqXMiDklHRwzHyOmKYcZ8
=Pi3c
-----END PGP SIGNATURE-----
 
A

Aahz

Regardless, Nicolas's example can be applied to the class too:

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)
 
H

Hyuga

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)

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 ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top