[英]Type hint for a file or file-like object?
Is there any correct type hint to use for a file or file-like object in Python?是否有任何正确的类型提示可用于 Python 中的文件或类文件对象? For example, how would I type-hint the return value of this function?
例如,我将如何键入提示此函数的返回值?
def foo() -> ???:
return open('bar')
Use either the typing.TextIO
or typing.BinaryIO
types, for files opened in text mode or binary mode respectively.分别对以文本模式或二进制模式打开的文件使用
typing.TextIO
或typing.BinaryIO
类型。
class
typing.IO
类
typing.IO
Wrapper namespace for I/O stream types.
I/O 流类型的包装命名空间。
This defines the generic type
IO[AnyStr]
and aliasesTextIO
andBinaryIO
for respectivelyIO[str]
andIO[bytes]
.这分别为
IO[str]
和IO[bytes]
定义了泛型类型IO[AnyStr]
和别名TextIO
和BinaryIO
。 These representing the types of I/O streams such as returned byopen()
.这些表示 I/O 流的类型,例如
open()
返回的。
The short answer:简短的回答:
from typing import TextIO
not just from typing import *
.from typing import TextIO
而不仅仅是from typing import *
。IO
to mean a file without specifying what kindIO
表示一个文件而不指定什么类型TextIO
or BinaryIO
if you know the typeTextIO
或BinaryIO
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
给出
Expected type 'BinaryIO', got 'TextIO' instead
的检查错误(在 PyCharm 中), Expected type 'BinaryIO', got 'TextIO' instead
您可以分别对文本文件和二进制文件使用TextIO和BinaryIO。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.