Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to use classes as dictionary keys in python?

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.

like image 530
zefciu Avatar asked Sep 17 '25 09:09

zefciu


1 Answers

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

like image 184
Marcin Avatar answered Sep 19 '25 04:09

Marcin