python / python/mypy

Infering return type as a union of all returns in type-checked functions

Open
#17,307 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Feature

Note: This is different than #4409 and #6646 which aim to change what is considered "annotated" and which functions are type-checked in the first place.

Mypy currently only type-check a function if its considered "annotated", ie: all parameters are annotated, or the return type is present (required for methods w/o parameters). Whilst mypy obviously can't infer a return type if it doesn't type-check the content of a function, I feel like methods that are checked could have their return type inferred as a union of whatever mypy think the type of the returns are.

Here's a very simple example comparing mypy and pyright/pylance
image
(same result in CLI)

Pitch

The idea would be to reduce clutter, and reduce the risk of hiding a useful true return type behind a more vague type.

Maybe there's a performance concern for libraries? (mypy having to read more code instead of stopping at a return annotation) How much is it? How much does caching help?

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.

Research direction

No implementation files or tests are named. Start by tracing how mypy decides whether a function is type-checked and how it handles explicit return annotations, then compare that behavior with the issue's example and the referenced issues. Done should mean checked functions infer a union of their return expressions, with performance and caching implications understood.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.