python / python/mypy

Document type inference behavior in case type declaration has (not) initializer

Open
#7,252 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

documentation priority-1-normal
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

In cases like this mypy doesn't narrow down the type in assignment:

x: Union[int, str] = 0
# type of x is Union[int, str] here!

Any assignment after the initial declaration will narrow the type down:

x: Union[int, str]
x = 0
# type of x is int here!

Document this behavior since it can be surprising. The motivation for this is that this behavior makes it easy to override the inferred type for a variable, which is sometimes useful.

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

Use the two examples in the issue as the documentation source: compare a declaration with an initializer against a later assignment, and explain the different narrowing behavior and why overriding the inferred type can be useful. Locate the appropriate mypy documentation section, add the explanation there, and verify that both examples and their inferred types are accurate.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.