[Python-ideas] Fix documentation for __instancecheck__

Chris Angelico rosuav at gmail.com
Sat Oct 27 21:59:13 EDT 2018


On Sun, Oct 28, 2018 at 12:53 PM Joy Diamond <python.gem at gmail.com> wrote:
>> - type(x) and x.__class__ don't necessarily agree; under what
>>   circumstances are each used?
>>
>> (I've asked this before, and either never got a good answer, or I can't
>> keep it straight in my head.)
>>
>> - what precisely does type(x) do?
>
>
> 1.  `type(x)` gets the true actual type of `x`.
> 2.  `x.__class__` gets the `.__class__` attribute for `x`, which by default gets the actual true type of `x`, but may be replace by the user to do other stuff.
>

Not that simple.

>>> class X:
...   cls = "X"
...
>>> class Y:
...   cls = "Y"
...
>>> x = X()
>>> x.__class__ = Y
>>> x.cls
'Y'
>>> type(x)
<class '__main__.Y'>

I don't know what the "true actual type" is, since I just changed it.
In this case, type() and __class__ do exactly the same thing. The only
way I know of (in Py3) to have them show different values is to make
__class__ a property, and if you do that, I have no idea what uses the
property and what uses type().

Maybe this needs to be actually documented somewhere. It keeps on
being a point of confusion.

ChrisA


More information about the Python-ideas mailing list