Raise exception vs. return None in functions?

后端 未结 5 1352
别跟我提以往
别跟我提以往 2020-12-22 20:49

What\'s better practice in a user-defined function in Python: raise an exception or return None? For example, I have a function that finds the mos

5条回答
  •  悲&欢浪女
    2020-12-22 21:42

    with python 3.5's typing:

    example function when returning None will be:

    def latestpdf(folder: str) -> Union[str, None]
    

    and when raising an exception will be:

    def latestpdf(folder: str) -> str 
    

    option 2 seem more readable and pythonic

    (+option to add comment to exception as stated earlier.)

提交回复
热议问题