8

I have a function that looks a bit like this. I want the function to accept any subclass of io.IOBase - in other words, any file-like object.

def import_csv_file(f:io.IOBase)->pandas.DataFrame:
    return pandas.read_csv(f)

When I view the object in IntelliJ, the JetBrains implementation of type-hinting rejects any input unless I provide exactly an instance of io.IOBase - but what if I want to pass in an instance of a sub-class of io.IOBase? Is there a way to change the type-hint to say that this is allowed?

Salim Fadhley
  • 6,975
  • 14
  • 46
  • 83

1 Answers1

6

If you annotate a function argument with the base class (io.IOBase in your case) then you can also pass instances of any subtype of the base class – inheritance applies to annotation types as well.

That said, you could use typing.IO as a generic type representing any I/O stream (and typing.TextIO and typing.BinaryIO for binary and text I/O streams respectively).

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • 1
    What would be a more general solution for this? If you had an `Animal` and a `BigAnimal` and wanted to write an API that accepted any object that was a subclass of `Animal`, how would you do that? – retsigam Sep 13 '22 at 17:41