python / python/mypy

Local type inference of numeric variables

Open
#8,747 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature needs discussion topic-usability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I have a very simple example program that produces surprising and (I think...) wrong behavior:

foo = 0

foo = 1.0

Running mypy against this file yields

test.py:3: error: Incompatible types in assignment (expression has type "float", variable has type "int")

But foo could(/should) be inferred as a float in this environment. I draw this conclusion from PEP-484

when an argument is annotated as having type float, an argument of type int is acceptable

(although this is not about function arguments per se).

I know that some improvements have been recently been made to type inference in 0.770 to use information from second (or subsequent) assignments, rather than just the first assignment. So maybe a widening from int to float could be implemented in the same way...?

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

Reproduce the behavior with the test.py example using mypy, then inspect the local type-inference changes referenced for version 0.770 and the relevant PEP-484 guidance. Done should establish whether a variable assigned an int may later widen to float and include coverage for the resulting assignment behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.