[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

isinstance() and multiple inheritance/ctypes

On 8/26/2015 5:21 PM, Rob Gaddi wrote:
> I'm running into some strangeness trying to work with the bitfield module
> from my ctypes-bitfield package (on PyPi).  I'm trying to use isinstance
> (), and it's kinda sorta lying to me.

isinstace(inst, klass) is implemented as
klass.__instancecheck__(inst) ==
type(klass).__instancecheck__(klass, inst)
In other words, __instancecheck__ is a metaclass method.
Reference Manual, 3.3.4. Customizing instance and subclass checks

> ----- IPython session (Python 3.4 under Linux) -------
> In [649]: bf.__mro__
> Out[649]: (bitfield._TD, _ctypes.Union, _ctypes._CData,
> bitfield.Bitfield, builtins.object)

Find the metaclasses with "for cl in bf.__mro__: print(type(bf))" and 
then take a look at the __instancecheck__ method if not 'type'.

> In [650]: isinstance(bf, bitfield.Bitfield)
> Out[650]: False
> In [651]: bf.__bases__
> Out[651]: (_ctypes.Union, bitfield.Bitfield)
> In [652]: bf.__bases__[1]
> Out[652]: bitfield.Bitfield
> In [653]: bf.__bases__[1] is bitfield.Bitfield
> Out[653]: True
> -------------------------------------------------------
> Is there an issue with isinstance and multiple inheritance?  Conversely
> is there an issue with isinstance and ctypes derived classes (Bitfield
> isn't, but Bitfield is a mixin that always works with Unions)  I know
> that ctypes classes can get really wonky on this stuff.
> More generally, is there any good way to introspect ctypes derived
> classes?  I have to figure out whether things are derived from Structure,
> Union, Array etc. through some ugly indirect methods, and have no idea
> why.

Terry Jan Reedy