python / python/mypy

Some string `in` `Union[bytes, str]` does not produce an error

Open
#9,822 1 comment 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

Given the following code

from typing import Union

foo: Union[str, bytes]  
"zoo" in foo  # no error
"zoo" + foo  # err: Unsupported operand types for + ("str" and "bytes")

I would have expected that mypy complains about str not compatible with bytes just like it does for the + operand.

I've tried the current typeshed version at 3d140160 because it just looked like there was a change here in Oct 2020 after mypy 0.790.

For example it now defines for class(str):

    def __contains__(self, o: Union[str, str]) -> bool: ...  # type: ignore
...
    def __iter__(self) -> Iterator[str]: ...

(__contains__ does not trigger here but its Union[str, str] is weird.)

Your Environment

mypy 0.790
python 3.8
builtin typeshed and @3d140160
Win 10

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 reproducing the Union[str, bytes] example with mypy 0.790, then inspect the typeshed definitions for str.contains and the related Union handling. Compare the diagnostics for "zoo" in foo and "zoo" + foo; done means the containment expression reports the incompatible str/bytes case consistently with the addition expression.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.