Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Post a Comment for "In Python Type-hinting, How Can I Make An Argument Accept Any Subclass Of A Base Class?"