isinstance() and multiple inheritance/ctypes

Chris Angelico rosuav at gmail.com
Wed Aug 26 19:12:55 EDT 2015


On Thu, Aug 27, 2015 at 7:21 AM, Rob Gaddi
<rgaddi at technologyhighland.invalid> 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.
>
> ----- IPython session (Python 3.4 under Linux) -------
> In [649]: bf.__mro__
> Out[649]: (bitfield._TD, _ctypes.Union, _ctypes._CData,
> bitfield.Bitfield, builtins.object)
>
> 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
> -------------------------------------------------------

You're omitting some context here, but after poking around with your
module a bit, I'm guessing you created bf somewhat thus?

>>> bf = bitfield.make_bf("bf", (("asdf",bitfield.c_uint,2),))
>>> bf
<class 'bitfield.bf'>
>>> bf.__mro__
(<class 'bitfield.bf'>, <class '_ctypes.Union'>, <class
'_ctypes._CData'>, <class 'bitfield.Bitfield'>, <class 'object'>)
>>> type(bf)
<class '_ctypes.UnionType'>
>>> type(bf).__mro__
(<class '_ctypes.UnionType'>, <class 'type'>, <class 'object'>)

If that's the case, then it's quite correct: bf is not a Bitfield, it
is a subclass of bitfield.

>>> isinstance(bf,type)
True
>>> isinstance(bf(),bitfield.Bitfield)
True
>>> issubclass(bf,bitfield.Bitfield)
True

Or is there a magic __isinstance__



More information about the Python-list mailing list