代码之家  ›  专栏  ›  技术社区  ›  thebjorn

mypy抱怨popen.stdout没有.readline

  •  0
  • thebjorn  · 技术社区  · 6 年前

    我试图告诉mypy以下函数应该产生Unicode字符串(即。 str 关于py3和 unicode 在py2上):

    # -*- coding: utf-8 -*-
    import os
    from typing import Iterator
    import subprocess
    
    def popen_readline():  # type: () -> Iterator[str]
        popen = subprocess.Popen(
            ['ls'],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            cwd=os.getcwd(),
            shell=True
        )
        for line in iter(popen.stdout.readline, b""):
            yield line.decode()
    

    mypy 没有 -2 标志在没有任何注释的情况下传递,但在添加 -2 我得到的国旗:

    c:\srv\tmp> mypy popenstdout.py -2
    popenstdout.py:14: error: Item "None" of "Optional[IO[Any]]" has no attribute "readline"
    popenstdout.py:15: error: Incompatible types in "yield" (actual type "unicode", expected type "str")
    

    这是我第一次尝试使用mypy。。是否可以指定此函数的类型,以便它可以在py2和py3上工作?

    () -> Iterator[Union[unicode,str]] 将删除py2上的第二个错误(但不是第一个);在py3上,它会导致:

    popenstdout.py:6: error: Name 'unicode' is not defined
    
    0 回复  |  直到 6 年前
    推荐文章