我有一个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
您建议如何使该代码兼容?
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]: ...
from typing import Optional
def get_csv_filename() -> Optional[str]:
...
实际上Optional[something]
等效于Union[None, something]
。