Bill Horvath
Bill Horvath

Reputation: 1717

Does type(a_subclass) return a singleton in Python?

I'm new to Python, and I need to compare two responses to type(a_subclass) for equality (i.e., I need to be sure the two subclasses of a parent class are exactly the same.) Can I safely assume that type returns singletons and use the is operator? Or is == necessary? Is there something else I should be worried about, like comparing package and module names?

Note the similar question here, to which the answers are confusing at best. I'm kinda looking for a 'yes' or a 'no.'

Upvotes: 3

Views: 99

Answers (1)

Davis Herring
Davis Herring

Reputation: 40013

I wouldn’t use the word “singleton” for type objects (in this question or the near-duplicate): a singleton is the only object of its type, and type(1) and type(None) are two objects of the same type (namely, type). The proper way to phrase this question would seem to be “Can two type objects represent the same type?”.

If so, it might be reasonable for them to compare ==, as suggested in the question. (Conversely, one could imagine different types comparing == based on something like their sizes or names, but we can ignore such useless possibilities.) However, types are mutable in Python, the simplest example being that you can assign static variables as Class.var=2. Plainly it must be possible to read that value with type(Class()).var, which implies that they are the same object. While it would be possible to implement such syntax through a proxy object, it is correct to assume that no such needless complexity is introduced (especially as it would involve additional memory allocation and reference counting overhead).

Seen from this perspective, the answer is almost a tautology: Python types are defined by the identity of their representative objects, so of course the same object must be used everywhere.

Upvotes: 3

Related Questions