Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   __class__ and type() implementation details in CPython (http://www.velocityreviews.com/forums/t957470-__class__-and-type-implementation-details-in-cpython.html)

Ivan Yurchenko 02-10-2013 11:35 AM

__class__ and type() implementation details in CPython
 
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. 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?

Thank you.

- Ivan Yurchenko.

Steven D'Aprano 02-10-2013 01:59 PM

Re: __class__ and type() implementation details in CPython
 
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/ti...s/typeobject.c


--
Steven



All times are GMT. The time now is 04:39 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.