python / python/mypy

__contains__ is not reconize as a None check

Open
#10,439 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I am struggling a bit on making mypy validate the type of an Iterable containing Optional:

def func_1(address: Address) -> Optional[float] :
    ...

def func_2(addresses: Tuple[Addresses, ...]) -> Optional[Tuple[float, ...]]:
    ordered_tuple = tuple(
        func_1(address)
        for address in addresses)
    return ordered_tuple if not None in ordered_tuple else None

Mypy seems to do not recognize the check if not None in ordered_tuple else None.
A workaround that I found is to check all the values returned by func_1 :

def func_1(address: Address) -> Optional[float] :
    ...

def func_2(addresses: Tuple[Addresses, ...]) -> Optional[Tuple[float, ...]]:
    ordered_list = []
    for address in addresses:
        value = func_1(address)
        if value is not None:
            ordered_list.append(value)
        else:
            return None
    return tuple(ordered_list)

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

No file or test is named in the issue. Start by reproducing the two examples with mypy and inspect the type-checking behavior for None in ordered_tuple; done means the first version is accepted with the intended Optional-to-non-Optional tuple narrowing, while the existing workaround remains valid.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.