__class__ and type() implementation details in CPython

I

Ivan Yurchenko

Hello.

I've done the following in CPython 2.7.3 and 3.3.0 (and also in PyPy 2.0b1):
(<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.
 
S

Steven D'Aprano

Ivan said:
Hello.

I've done the following in CPython 2.7.3 and 3.3.0 (and also in PyPy
2.0b1):

(<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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top