[Python-Dev] type(obj) vs. obj.class (original) (raw)
Serhiy Storchaka storchaka at gmail.com
Tue Oct 20 04:21:28 EDT 2015
- Previous message (by thread): [Python-Dev] type(obj) vs. obj.__class__
- Next message (by thread): [Python-Dev] type(obj) vs. obj.__class__
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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).
- Previous message (by thread): [Python-Dev] type(obj) vs. obj.__class__
- Next message (by thread): [Python-Dev] type(obj) vs. obj.__class__
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]