python / python/mypy

list.append seems to break return type checker

Open
#8,734 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Hello, concerning the function below:

from typing import List
def foo() -> List[int]:
    listings = None
    if 2 != 2:
        listings = list()
        listings.append(1)
    return listings

I expected:
Incompatible return value type (got "Optional[List[int]]", expected "List[int]")

I got no error

This one does throw the expected error (same config):

from typing import List
def foo() -> List[int]:
    listings = None
    if 2 != 2:
        listings = [1]
    return listings

running mypy 0.770 on python 3.8

I would appreciate it if you could tell me if I am doing something wrong :)

Have a good day !

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 two snippets with mypy 0.770 on Python 3.8 and compare the inferred type of listings before the return. Trace the handling of list.append versus the list literal, then add a regression test showing that both cases produce the expected Optional[List[int]] return-value error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
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.