This rule raises an issue when a special method returns an object of an unexpected type.
Python allows developers to customize how code is interpreted by defining special methods (also called magic methods). For example, it is possible
to define the objects own truthiness or falsiness by iverriding __bool__ method. It is invoked when the built-in bool()
function is called on an object. The bool() function returns True or False based on the truth value of the
object.
The Python interpreter will call these methods when performing the operation they’re associated with. Each special method expects a specific return
type. Calls to a special method will throw a TypeError if its return type is incorrect.
An issue will be raised when one of the following methods doesn’t return the indicated type:
__bool__ method should return bool __index__ method should return integer __repr__ method should return string __str__ method should return string __bytes__ method should return bytes __hash__ method should return integer __format__ method should return string __getnewargs__ method should return tuple __getnewargs_ex__ method should return something which is of the form tuple(tuple, dict) Make sure to return a value of the same type as defined in the Python documentation for each special method.
class MyClass:
def __bool__(self):
return 0 # Noncompliant: Return value of type bool here.
obj1 = MyClass()
print(bool(obj1)) # TypeError: __bool__ should return bool, returned int
class MyClass:
def __bool__(self):
return False
obj1 = MyClass()
print(bool(obj1))