简体   繁体   中英

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?

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM