如何输入注释csv.writer返回的对象?

MrL*_*eeh 7 python mypy

我想将类型注释应用于返回的对象,csv.writer以符合更大的代码库.不幸的是我无法弄清楚拟合返回类型.

>>> import csv
>>> writer = csv.writer(open('outfile.csv', 'w'))
>>> type(writer)
<class '_csv.writer'>
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用此类名:

>>> import _csv
>>> writer: _csv.writer = csv.writer(open('outfile.csv', 'w'))
Run Code Online (Sandbox Code Playgroud)

我收到以下mypy错误:

Invalid type "_csv.writer"
Run Code Online (Sandbox Code Playgroud)

有人知道在这种情况下使用哪种类型.当然我可以使用,typing.Any但这会使类型注释的意义无效.

eth*_*nhs 11

通常,当事情表现得很奇怪时,这是输入的符号没有完全映射到运行时。如果您查看typeshed 中的_csv ,您将看到该类型被命名为_writer。所以你应该可以将注释添加到_csv._writer.

  • @DanielChin 将其设为字符串文字 `import _csv` 然后 `f: '_csv._writer'` (3认同)
  • 这会导致“错误:名称'csv._writer'未定义” (2认同)
  • 您需要使用“_csv._writer” (2认同)

Tom*_*Tom 7

我遇到了 typeshed defs 的问题,最终使用了以下内容:

class Writer(Protocol):
    def writerow(self, row: Iterable[Any]) -> Any:
        ...

    def writerows(self, rows: Iterable[Iterable[Any]]) -> None:
        ...


Reader = Iterator[Any]
Run Code Online (Sandbox Code Playgroud)
writer: Writer = csv.writer(open('outfile.csv', 'w'))
reader: Reader = csv.writer(open('outfile.csv', 'w'))
Run Code Online (Sandbox Code Playgroud)