More precise type checking of NotImplemented and operator overloading

Open
#363 3 comments 13 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
30/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
python

Research direction

No files, tests, or entry points are named. Start by locating how mypy represents and checks NotImplemented and how operator methods are identified; compare those paths with the two examples in the issue. Done means NotImplemented is accepted for the relevant operator returns but rejected for the ordinary bool return unless the annotation permits it.

Written by the indexing model from the issue text.

Description

bug priority-1-normal

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
Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.