1

I have a Python script that starts with a method searching for a CSV file in the current directory or downloads a directory to make some processing. If no CSV file is found, the program should not run and exit with an error message.

I type annotated a tentative method as follows:

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()

If I type check with eg. pytype I get the error:

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

What would you recommend doing to make this code compliant?

4

2 回答 2

2

PEP 484 的这一部分可能会有所帮助。我没有安装mypypytype来尝试它,但也许这会起作用:

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]:
...
于 2020-01-01T01:33:38.410 回答
0

Steve Bremer 的 response的想法来看,这个问题可以用一种更简单的方法来解决:

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

其实Optional[something]等价于Union[None, something]

于 2020-01-02T01:35:19.640 回答