开发者

return tuple from a method

I am writing a method which returns a tuple on success but None on failure. I have not yet finalized on None 开发者_如何学JAVA(as a failure case return) but it is one of the choices. Can we return -1,-1 for failure case? I am looking for best pythonic way to achieve this so that unpacking is easy.

Please let me know how we can improve it. Pseudo code is given below

 def myFunc(self):
     if self.validate() != 0:
         return
     x,y = self.getXY()

     return x,y


If there is a failure, why don't you raise an exception?

You can of course return (-1, -1) as failure, but it would not be a good solution in my opinion.

Remember that in Python EAFP (Easier to Ask Forgiveness than Permission) is favoured over LBYL (Look Before You Leap).

This means that it is considered better to just write code under the hypothesis that all works and then catching the appropriate exceptions.

Your code could then become

 def myFunc(self):
     if self.validate() != 0:
         raise CustomNotValidatedException()
     x,y = self.getXY()

     return x,y

I would improve your code in the following ways:

  • make self.validate() return 0 when the result is not positive, so that you can change the second row in a more pythonic way:

     if not self.validate():
    
  • remove the intermediate x, y variables by changing the return statement to:

     return self.getXY()
    

Finally, you could just raise the exception inside getXY() and use directly this method in your code.


If this is to catch programming errors, then assert is cleaner.

def my_function(self):
    assert self.validate()
    return self.x, self.y

If it's to catch run-time errors, perhaps with user-provided data, then an exception is better.

def my_function(self):
    if not self.validate():
        raise ValidationError
    return self.x, self.y

A good alternative here would for self.validate() to raise validation errors itself: this would allow for example a message to be provided giving the reason for the validation error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜