4

I am about to write a function that finds a correct handler for a class. To achieve it I want to use a mapping from classes to handlers. I've already checked that it is possible to use classes as dictionary keys, however I am not completely sure if it is the right think to do.

My main concern is, if it is guaranteed that if I have a class imported in two different modules, these two will have the same hash. But maybe there are some other aspects that I should consider.

If idea of using classes itself is wrong, then I will use classnames, but that would require me to keep them unique, so I would prefer to use classes itself.

EDIT: I have made a test:

# file: a.py
import datetime                                                                 
D = datetime.datetime 

# file: b.py
import datetime
from a import D
print hash(D) == hash(datetime.datetime)

This prints "True", but I am still not sure if there is a way for it to be False for the same class.

zefciu
  • 1,967
  • 2
  • 17
  • 39

4 Answers4

3

It's perfectly valid, but note that what you are doing is fake-adding a method to that class.

Consider whether it would be better to just add appropriate methods to your classes, either in the normal way, or possibly just by guerilla-patching. (It might not be, but consider it).

Marcin
  • 48,559
  • 18
  • 128
  • 201
  • 1
    Thanks. I still believe that it is necessary for the system I'm trying to implement, but thanks for the warning. – zefciu Feb 29 '12 at 16:26
2

This is perfectly okay, since classes are objects themselves. For objects the hash key is their memory location which is guranteed to be unique. Let me get a reference...

Constantinius
  • 34,183
  • 8
  • 77
  • 85
  • I am not worried about lack of uniqueness (that would yield false positives). I am worried about the same class stored in two places in memory (which would yield false negative). – zefciu Feb 29 '12 at 09:35
  • 2
    @zefciu, The same class cannot be stored in two places in memory, otherwise it's not the same... – warvariuc Feb 29 '12 at 09:52
2

It's perfectly valid to use a class as a dictionary key, I've done it a couple of times already. However, inheritance will not work, that is, a handler for a class will not apply to its subclasses which may not be what you want. __mro__ could be useful in that case, but this solution seems wrong to me.

Sylvain Prat
  • 291
  • 3
  • 10
0

however, in python3.6 this does not work with subclasses anymore. My example is a hierarchy of 3 classes and it fails with

TypeError: unhashable type: 'SubClassOfSubclass'

U.V.
  • 572
  • 4
  • 11