This rule raises an issue when a special method returns an object of an unexpected type.

Why is this an issue?

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:

How to fix it

Make sure to return a value of the same type as defined in the Python documentation for each special method.

Code examples

Noncompliant code example

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

Compliant solution

class MyClass:
    def __bool__(self):
        return False

obj1 = MyClass()
print(bool(obj1))

Resources

Documentation