Raise exception vs. return None in functions?

后端 未结 5 1347
别跟我提以往
别跟我提以往 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:20

    I would make a couple suggestions before answering your question as it may answer the question for you.

    • Always name your functions descriptive. latestpdf means very little to anyone but looking over your function latestpdf() gets the latest pdf. I would suggest that you name it getLatestPdfFromFolder(folder).

    As soon as I did this it became clear what it should return.. If there isn't a pdf raise an exception. But wait there more..

    • Keep the functions clearly defined. Since it's not apparent what somefuc is supposed to do and it's not (apparently) obvious how it relates to getting the latest pdf I would suggest you move it out. This makes the code much more readable.

    for folder in folders:
       try:
           latest = getLatestPdfFromFolder(folder)
           results = somefuc(latest)
       except IOError: pass
    

    Hope this helps!

提交回复
热议问题