Paul Manta
Paul Manta

Reputation: 31597

Dictionary of types

In Python, what is the more efficient way of using types as dictionary keys? Given a classObject, should I use classObject.__name__ or the object itself directly?

Upvotes: 2

Views: 144

Answers (2)

Maxy-B
Maxy-B

Reputation: 2832

It depends on what you mean by "more efficient". As @phihag pointed out, the class object itself hashes just as well as the __name__ string, so they are equally fine dictionary keys from that perspective. Where they might differ depends on what you want to do with the keys. For example, if you ever want to programmatically instantiate the class corresponding to one of your dictionary keys, it is pretty straight forward to do:

class A(object): pass
mydict[A] = 'blah'

# ...

for t,v in mydict.iteritems():
    if v=='blah':
        o = t() # instantiate the class/key

This would be much trickier to do if the dict keys were __name__ strings rather than actual class objects.

Edit: well, somewhat trickier. You'd have to do something like:

o = globals()[t]()

But as @phihag mentioned, it is possible for distinct classes to have the same __name__, and that could be a problem.

Upvotes: 0

phihag
phihag

Reputation: 288230

Since type names don't have to be unique across modules, you must use the type (classObject) itself.

Luckily, types will automatically have a non-trivial hash value:

>>> class A(object): pass
>>> class B(object): pass
>>> hash(A)
2579460
>>> hash(B)
2579600

Upvotes: 3

Related Questions