What is the type of NotImplemented?

Viewed 1506

I have the following function:

   def __eq__(self, other: object) -> Union[bool, NotImplemented]:
        try:
            for attr in ["name", "variable_type"]:
                if getattr(self, attr) != getattr(other, attr):
                    return False
            return True
        except AttributeError:
            return NotImplemented  # Expression has type "Any"

I'm running mypy, and it's telling me that NotImplemented is of type "Any", which it obviously doesn't like.

Is there any better type I can use to remove this error? Or should I just put a type: ignore in and move on? (In addition, is my use of NotImplemented in the return type correct?)

1 Answers

It is NotImplementedType.

type(NotImplemented)                                                                                                                
# NotImplementedType

Meaning, you can define your function like this:

def foo(self, other: object) -> Union[bool, type(NotImplemented)]: 
     pass 

Now, help(foo) gives,

help(foo)                                                                                                                           
# Help on function foo in module __main__:
#  
# foo(self, other:object) -> Union[bool, NotImplementedType]

As an aside, it is worth mentioning that NotImplemented is a singleton object used with a very specific purpose (it is used to indicate that a particular operation is not defined on an object). You almost never really need to access its type, and to my knowledge there's nowhere you can import NotImplementedType from.

I would just define __eq__ to be

def foo(self, other: object) -> bool: 
     pass 

When NotImplemented is returned, it should be understood that it is a not a valid result, rather an indication that the equality comparison is invalid.

Related