python / python/mypy

Truthiness of None Does not Narrow Optional Types

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

Nobody has claimed this yet.

false-positive feature needs discussion priority-2-low topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Note: if you are reporting a wrong signature of a function or a class in
the standard library, then the typeshed tracker is better suited
for this report: https://github.com/python/typeshed/issues

Please provide more information to help us understand the issue:

  • Are you reporting a bug, or opening a feature request?
    I believe this is a bug

  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.

from typing import Optional

def the_method(maybe_int: Optional[int]):
    can_divide = bool(maybe_int)
    if can_divide:
        100 / maybe_int
  • What is the actual behavior/output?
error: Unsupported operand types for / ("int" and "None")
  • What is the behavior/output you expect?
    I would think that the conditional branch would recognize that only int values would ever make it there

  • What are the versions of mypy and Python you are using?
    mypy 0.720 with Python 3.7.3

  • Do you see the same issue after installing mypy from Git master?
    Yes still exists on master

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 with the minimal Python repro in the issue and trace mypy's truthiness-based type-narrowing entry point. No source file or test is named in the report; done means the conditional branch narrows Optional[int] sufficiently for 100 / maybe_int to type-check, with regression coverage.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.