Skip to content

More precise type checking of NotImplemented and operator overloading #363

Open

Description

@JukkaL

NotImplemented should be implicitly a valid return value of operator methods such as __lt__, __add__, but it should be flagged as an error to return it elsewhere (unless, maybe, the return type includes a suitable type such as typing.NotImplementedType).

Currently NotImplemented has type Any which allows it to be used in any context, which is wrong.

This should be fine:

def __lt__(self, x: int) -> bool:
    if isinstance(x, int):
        return ...
    return NotImplemented

This should not be fine:

def f() -> bool:
    return NotImplemented

Activity

  1. mthuurne commented on Dec 7, 2020

    @mthuurne
    Contributor

    (unless, maybe, the return type includes a suitable type such as typing.NotImplementedType).

    There is no typing.NotImplementedType at the moment though. I think Literal[NotImplemented] would be more elegant anyway, but that is not accepted by mypy 0.790.

  2. brianrodri commented on Aug 8, 2021

    @brianrodri

    Could we please get some official guidance on how to workaround this issue in the short term?

    I understand the complexity at stake here after reading the referenced/referencing issues, but I think it'd be helpful to have an "official workaround" until this gets resolved.

    From my understanding, the problem is:

    def __eq__(self, other: Any) -> bool: ... # Doesn't work.
    def __eq__(self, other: Any) -> Union[bool, NotImplemented]: ... # Doesn't work.
    def __eq__(self, other: Any) -> Any: ... # Only option?
  3. 0dminnimda commented on Jul 5, 2022

    @0dminnimda

    Are there any updates on this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions