类型提示在Python 3.7+中返回字符串或错误的方法

问题描述 投票:1回答:2

我有一个python脚本,其开头是在当前目录中搜索CSV文件或下载目录以进行一些处理的方法。如果未找到文件CSV文件,则该程序不应运行并退出并显示错误消息。

我在下面输入了一种临时方法的注释:

import glob
import os


def get_csv_filename() -> str:
    """ Returns first csv filename in current folder or Downloads folder """
    csv_filenames = glob.glob('*.csv')
    if csv_filenames:
        return csv_filenames[0]
    home = os.path.expanduser("~")
    csv_filenames = glob.glob(home + "/Downloads/*.csv")
    if csv_filenames:
        return csv_filenames[0]
    # if I don't use return, I also get problems with pylint
    return exit("Error: no file found, check the documentation for more info.")


def main() -> None:
    """ Reads a CSV and does some processing """
    filename = get_csv_filename()

如果我输入带有例如pytype我得到错误:

get_csv_filename: bad option in return type [bad-return-type]
  Expected: str
  Actually returned: None

您建议如何使该代码兼容?

python-3.x type-hinting mypy pytype
2个回答
1
投票
This section可能会有所帮助。我没有安装

mypy或pytype进行尝试,但是也许可以使用:

from typing import NoReturn def get_csv_filename() -> str: """ Returns first csv filename in current folder or Downloads folder """ csv_filenames = glob.glob('*.csv') if csv_filenames: return csv_filenames[0] ... stop("Error: no file found, check the documentation for more info.") return "" def stop(msg) -> NoReturn: exit(msg)
另一个选择是:

from typing import Union def get_csv_filename() -> Union[None, str]: ...


0
投票
实际上基于Steve Bremer响应的思想,我实际上是通过一种更简单的方法解决了该问题:

from typing import Optional def get_csv_filename() -> Optional[str]: ...

实际上Optional[something]等效于Union[None, something]
© www.soinside.com 2019 - 2024. All rights reserved.