Type hint for a file or file-like object?

前端 未结 2 1147
执念已碎
执念已碎 2021-01-31 12:55

Is there any correct type hint to use for a file or file-like object in Python? For example, how would I type-hint the return value of this function?

def foo():
         


        
2条回答
  •  一整个雨季
    2021-01-31 13:50

    The short answer:

    • You need to be explicit. That is from typing import TextIO not just from typing import *.
    • Use IO to mean a file without specifying what kind
    • Use TextIO or BinaryIO if you know the type
    • You cannot currently specify it be opened for write or its encoding.

    As an example:

    from typing import BinaryIO
    
    def binf(inf: BinaryIO):
        pass
    
    with open('x') as f:
        binf(f)
    

    gives an inspection error (in PyCharm) of Expected type 'BinaryIO', got 'TextIO' instead

提交回复
热议问题