python / python/mypy

Type detection broken on attribute override and not-equal-assertion

Open
#11,226 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

I commonly find myself writing simplified list init parameters. So, if the user provides only a type X, I automatically convert that to list type [X]. In doing so, I found two issue that prevent a proper type detection. See the example code below.

To Reproduce

#!/usr/bin/env python3
from typing import Union, List, Optional

def test(a: Union[List[str], str, None] = None) -> Optional[List[str]]:
    if type(a) == str:
        a = [a]
    assert(type(a) != str)
    return a

Expected Behavior

  1. First, the type(a) == str check and consequent list assignment should remove the str type from the Union choices.
  2. Second, the assert(!=) check should also remove the str type from the Union options.

Actual Behavior

Both checks do not work and the type is still guessed incorrectly:

screen

Your Environment

  • Mypy version used: 0.910
  • Mypy command-line flags: pip install
  • Mypy configuration options from mypy.ini (and other config files): -
  • Python version used: 3.8
  • Operating system and version: macOS 10.15

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

Start by running the provided Python reproducer against mypy and inspect the type-narrowing behavior for the type(a) == str assignment and the assert(type(a) != str) check. Done means both branches remove str from the inferred Union and the function is accepted with the expected Optional[List[str]] return type.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
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.