Disallow object creation in Python constructor

How does the handle correctly reject object creation in the Python constructor? Consider the object:

class Triangle: def __init__(self, a, b, c): sides = [a, b, c] sides.sort() if sides[0]+sides[1] < sides[2]: return None self._a = a self._b = b self._c = c 

If the sides are not logical for a triangle, I would like to refuse to create a Triangle object. Returning None does not prevent the creation of the Triangle object, and returning False raises an exception. What is the right way to handle this? Should I throw some type of exception when the wrong parameters are specified?

+4
source share
2 answers

Or throw an exception

 class Triangle: def __init__(self, a, b, c): sides = [a, b, c] sides.sort() if sides[0]+sides[1] < sides[2]: raise ValueError() self._a = a self._b = b self._c = c 

or use assert (which raises the exception itself)

 class Triangle: def __init__(self, a, b, c): sides = [a, b, c] sides.sort() assert sides[0]+sides[1] >= sides[2] self._a = a self._b = b self._c = c 

Which one is more appropriate depends on whether invalid values ​​should be selected as part of your API (first version) or only to search for programmer errors (second version, because statements will be skipped if you pass the -O "optimized" flag to the interpreter python).

+6
source

Returning a value (even None ) from the constructor is invalid

As you suggested, an exception should be thrown.

 class Triangle: def __init__(self, a, b, c): sides = [a, b, c] sides.sort() if sides[0]+sides[1] < sides[2]: raise ValueError() self._a = a self._b = b self._c = c 
+2
source

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


All Articles