1

EDIT: It was my bad. I should have used issubclass instead of isinstance, as suggested in @kevin-mayo 's answer. Then everything works.

I recently stumbled upon a weird behaviour of pycharm's type hinting, which later revealed a trouble with python itself. I have a method which takes a stream, so I set the type as io.BaseIO. However, when I passed a BytesIO to it, it gave me a warning. I checked the following:

>>> io.BytesIO.__mro__
(<class '_io.BytesIO'>, <class '_io._BufferedIOBase'>, <class '_io._IOBase'>, <class 'object'>)
>>> isinstance(io.BytesIO, io.IOBase)
False

This contradicts what Python docs say, so I'm really confused.

I'm using Python 3.7.

I realize the duck typing way of doing this, but keep in mind that I'm not making a strict type check, but a convenient type hint.

abel1502
  • 955
  • 4
  • 14
  • I'm voting to close this question as a duplicate of [How do I check (at runtime) if one class is a subclass of another?](https://stackoverflow.com/questions/4912972/how-do-i-check-at-runtime-if-one-class-is-a-subclass-of-another) – mkrieger1 Oct 16 '21 at 18:37
  • @mkrieger1 The question isn't really a duplicate, but rather useless to anyone but me, since it was my personal dumb mistake. I can't seem to find a button to close my own question, but I can delete it if I should – abel1502 Oct 17 '21 at 16:19

1 Answers1

3

That's because

isinstance(io.BytesIO, io.IOBase)

is to check whether it is the instance of the class,

You may need to use issubclass(io.BytesIO, io.IOBase) to check them

Kevin Mayo
  • 1,089
  • 6
  • 19
  • OMG, You're right. I'm so dumb). So that makes it pycharm glitch, but I suppose I can live with that) – abel1502 Jul 17 '20 at 12:21
  • @abel1502 I think the cause is `pycharm` doesn't know the type of your variable due to python is a dynamic language, You could use annotation to let pycharm "think" it is a `IOBase`.Or you could try a useful plugin called `Kite`. – Kevin Mayo Jul 17 '20 at 12:27
  • @Kite, no, it did know the type - it said something like "BytesIO passed where IOBase was expected". + The code was like `stream = io.BytesIO()\nself.write(stream)`. But rebooting pycharm has actually fixed this as well – abel1502 Jul 17 '20 at 15:49