Salim Fadhley
Salim Fadhley

Reputation: 8175

In python type-hinting, how can I make an argument accept any subclass of a base class?

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?

Upvotes: 8

Views: 5417

Answers (1)

Eugene Yarmash
Eugene Yarmash

Reputation: 149726

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).

Upvotes: 6

Related Questions