pythonmypypython-typingpytype

Type hinting a method that returns a string or error in Python 3.7+


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?


Solution

  • From the ideas of Steve Bremer's response, the problem can be solved with a simpler approach:

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

    In fact, Optional[something] is equivalent to Union[None, something].