__class__ and type() implementation details in CPython
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Feb 10 08:59:36 EST 2013
Ivan Yurchenko wrote:
> Hello.
>
> I've done the following in CPython 2.7.3 and 3.3.0 (and also in PyPy
> 2.0b1):
>
>>>> import weakref
>>>> x = set()
>>>> y = weakref.proxy(x)
>>>> x.__class__, type(x), isinstance(x, set)
> (<class 'set'>, <class 'set'>, True)
>>>> y.__class__, type(y), isinstance(y, set)
> (<class 'set'>, <class 'weakproxy'>, True)
>
> So, type doesn't use object's __class__ to determine its class.
Sometimes it does:
py> class X(object): pass
...
py> class Y(object): pass
...
py> x = X()
py> x
<__main__.X object at 0xb7c9adac>
py> x.__class__ = Y
py> x
<__main__.Y object at 0xb7c9adac>
py> type(x)
<class '__main__.Y'>
I believe that it depends on whether the instance being inspected is a
heap-type (e.g. pure-Python object) or not.
> I'm
> looking for some CPyhton implementation details - how does class
> identification with type() work? According to CPython's sources it looks
> like there is a "marker" of actual object's class associated with each
> PyObject - _typeobject struct, which is used to identify the class by
> type(). Am I right?
I'm not an expert on the CPython implementation, but I believe the code you
want is buried somewhere in here:
http://hg.python.org/cpython/file/tip/Objects/typeobject.c
--
Steven
More information about the Python-list
mailing list