Returning a tuple from a method

I am writing a method that returns a tuple, but Noneon error. I have not finalized yet None(as a return to failure), but this is one option. Can we return -1,-1for a case of failure? I am looking for the best pythonic way to achieve this so that unpacking is easy.

Please let me know how we can improve it. The pseudo code is below

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

     return x,y
+3
source share
2 answers

If a failure occurs, why not throw an exception?

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

Remember that in Python EAFP (easier to ask for forgiveness than permission) is preferable to LBYL (see before jumping).

, , , .

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

     return x,y

:

  • make self.validate() 0, , :

     if not self.validate():
    
  • x, y, return :

     return self.getXY()
    

, getXY() .

+14

, , assert .

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

, , , .

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

self.validate() : , , , .

+3

Source: https://habr.com/ru/post/1789466/