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

后端 未结 3 1208
醉话见心
醉话见心 2021-01-18 10:36

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_         


        
3条回答
  •  野的像风
    2021-01-18 11:04

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

提交回复
热议问题