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

后端 未结 6 603
醉梦人生
醉梦人生 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

    It'd be better to raise an exception than return a special value. This is exactly what exceptions were designed for, to replace error codes with a more robust and structured error-handling mechanism.

    class IntersectException(Exception):
        def __init__(self, msg):
            self.msg = msg
        def __str__(self):
            return self.msg
    
    def intersect_two_lists(self, list1, list2):
        if not list1: raise IntersectException("list1 must not be empty.")
        if not list2: raise IntersectException("list2 must not be empty.")
    
        #http://bytes.com/topic/python/answers/19083-standard
        return filter(lambda x:x in list1,list2)
    

    In this specific case though I'd probably just drop the tests. There's nothing wrong with intersecting empty lists, really. Also lambda is sort of discouraged these days in preference to list comprehensions. See Find intersection of two lists? for a couple of ways to write this without using lambda.

提交回复
热议问题