On 18.10.15 00:45, Eric Snow wrote:
So, would it make sense to establish some concrete guidelines about when to use type(obj) vs. obj.__class__? If so, what would those be? It may also be helpful to enumerate use cases for "type(obj) is not obj.__class__".
My conclusion of this discussion. In Python 3 type(obj) and obj.__class__ are the same in common case. Assigning obj.__class__ is a way to change type(obj). If the assignment is successful, type(obj) becomes the same as obj.__class__. This is used in importlib for lazy importing and some clever classes like the RingBuffer recipe. But __class__ assignment has many restrictions, and changing Python to C implementation or adding __slots__ for sure adds new restrictions. obj.__class__ is different from type(obj) in proxy classes like weakref or Mock. isinstance() and pickle take __class__ to account to support proxies. Unless we write proxy class or code that should handle proxy classes, we shouldn't care about the difference between type(obj) and obj.__class__, and can use what is the more convenient. In Python this is obj.__class__ (avoids globals lookup), and in C this is type(obj) (much simpler and reliable code).