python / python/mypy

Optional types not being narrowed after a logical-and followed by a test of one of the operands

Open
#6,835 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

false-positive feature priority-2-low
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

(Sorry if the title is overly specific)

  • Are you reporting a bug, or opening a feature request?

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 get_org_id(org_name: str) -> str:
    return 'some_org_id'

def create(org_name: Optional[str], org_id: Optional[str]):
    if not org_name and not org_id:
        raise ValueError('No org specified')
    if not org_id:
        org_id = get_org_id(org_name)
  • What is the actual behavior/output?

The inferred type of org_name at the last line is Optional[str] (technically Union[builtins.str, None]).

  • What is the behavior/output you expect?

The type should be narrowed to str.

  • What are the versions of mypy and Python you are using?
    Do you see the same issue after installing mypy from Git master?

Python 3.7.3
mypy: 0.701

  • What are the mypy flags you are using? (For example --strict-optional)

No flags

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 confirm the inferred type of org_name after the logical-and conditions. Trace the type-narrowing behavior for org_name and org_id, then add coverage for this case. Done means org_name is inferred as str at the get_org_id call without breaking related optional-type narrowing.

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
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.