I
I
Ivanhoe2013-03-17 22:22:10
Python
Ivanhoe, 2013-03-17 22:22:10

I don't understand the behavior of type with weakref?

Hello Habr.
I have always been sure that in Python for objects of new classes the attribute x.__class__and type(x)will have the same value. However, if you do this (tested with Python 2.7.3 and 3.3.0, and 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)
we'll see that for weakref.proxyy.__class__matches the wrapped type (I guess weakref.proxyjust spoofing an attribute to mimic the wrapped object), and even isinstancerecognizes it as a set. But at the same time , it typeindicates its true type - weakproxy. It turns out that it typedoes not use its attribute to determine the type of an argument __class__. It turns out that he typeuses some "more reliable" source to determine the type? Is it possible to access it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivanhoe, 2013-03-26
@Ivanhoe

The answer is this.
Inside the interpreter (CPython), each Python object is represented by a C structure PyObject(file object.h), in which one of the fields is ob_type, a pointer to a structure _typeobjectthat defines the "real" type of the object. type(x)and descriptor object.__class__refer to the type of this field. But __class__it can be overridden, which is what weakref.proxy. At the same time type(x), it will still continue to access ob_typeand the result of its determination cannot be changed.

S
smglab, 2013-03-18
@smglab

read this book www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question