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?
In inheritance, a class (usually called superclass) is inherited by another class (usually called subclass). The subclass adds some attributes to superclass. Below is a sample Python program to show how inheritance is implemented in Python. # Base or Super class.
Type hints improve IDEs and linters. They make it much easier to statically reason about your code. Type hints help you build and maintain a cleaner architecture. The act of writing type hints forces you to think about the types in your program.
In a type hint, if we specify a type (class), then we mark the variable as containing an instance of that type. To specify that a variable instead contains a type, we need to use type[Cls] (or the old syntax typing. Type ).
Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False. Parameters: Object: class to be checked.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With