Best practice in python for return value on error vs. success

后端 未结 6 605
醉梦人生
醉梦人生 2020-12-07 18:41

In general, let\'s say you have a method like the below.

def intersect_two_lists(self, list1, list2):
    if not list1:
        self.trap_e         


        
6条回答
  •  醉话见心
    2020-12-07 19:13

    For collections (lists, sets, dicts, etc.) returning an empty collection is the obvious choice because it allows your call site logic to remain clear of defensive logic. More explicitly, an empty collection is still a perfectly good answer from a function from which you expect a collection, you do not have to check that the result is of any other type, and can continue your business logic in a clean manner.

    For non collection results there are several ways to handle conditional returns:

    1. As many answers have already explained, using Exceptions is one way to solve this, and is idiomatic python. However, it is my preference not to use Exceptions for control flow as I find it creates ambiguity on the intentions of an Exception. Instead, raise Exceptions in actual exceptional situations.
    2. Another solution is to return None instead of your expected result but this forces a user to add defensive checks everywhere in their call sites, obfuscating the actual business logic they are trying to actually execute.
    3. A third way is to use a collection type that is only capable of holding a single element (or being explicitly empty). This is called an Optional and is my preferred method because it allows you to keep clean call site logic. However, python does not have a built in optional type, so I use my own. I published it in a tiny library called optional.py if anyone wants to give it a try. You can install it using pip install optional.py. I welcome comments, feature requests, and contributions.

提交回复
热议问题