pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

`if isinstance(val, (str, bytes))` ignored

Open MarcoGorelli opened this issue 6 months ago • 2 comments

Describe the Bug

If I run this:

from typing import reveal_type, Any, Iterable


def arrlen(obj: Any) -> int | None:
    ...

def main(a: float | str | bytes | Iterable[Any]) -> None:
    if isinstance(a, (str, bytes)):
        pass
    elif arrlen(a) is not None:
        reveal_type(a)

I get

(scratch) mgorelli@marcoslaptop:~/scratch$ pyright t.py
/home/mgorelli/scratch/t.py
  /home/mgorelli/scratch/t.py:11:21 - information: Type of "a" is "float | int | Iterable[Any]"
0 errors, 0 warnings, 1 information
(scratch) mgorelli@marcoslaptop:~/scratch$ ty check t.py
info[revealed-type]: Revealed type
  --> t.py:11:21
   |
11 |         reveal_type(a)
   |                     ^ `int | float | (Iterable[Any] & ~str & ~bytes)`
   |

Found 1 diagnostic
(scratch) mgorelli@marcoslaptop:~/scratch$ pyrefly check t.py
 INFO revealed type: Iterable[Any] | bytes | float | str [reveal-type]
  --> t.py:11:20
   |
11 |         reveal_type(a)
   |                    ---
   |
 INFO 0 errors

Note how pyrefly includes str and bytes - shouldn't it rule them out, based on the first if statement?

Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN2UYANxiooAfSbEYAGjoBBdKTkBJBjEqpssADro9ezDDB1UlSrHQAKXNgBWiBUoCUdALQA%2BTun4AfOgByuOgwiHp0EXSE0QZYxnQ0qKxWqI5gULiofnRwDJR0-tik6nAFdGoaWrAA2oqkALqunoHBoeGRECYQcKy5GADGMClyVrmUckUlzs5h6JHzdMSocHDtETBQnabmlimu3XTouPxBIbMLkYIiYpLMQ6jOIDIgZILppIQMtFAUAMR0AAVSG8oKQchgcAQ6P1gpA2ABXTQMCDBQh6f4AZRgMDoAAsGAxiHBEAB6EmvYygwi8NgkmDoEmYXD9OAkmHoOGIrIohl0MC8UxCJJQKo49mcpE8ui4YjI4JwNHoMgMXHBNwiSg9YJ0AC8dB0IAAzIQAIwAJgNemqGmomvqenh6C4PD4MEwbkwEEE-WRIl1dAA5BA2EdBAG9EcGG5BABHeFet1uADWMFIblQ-UGK39AYA7mZ0OH0CAAL7PDO%2BmAAMWgMAoaCweCIZFLQA

(Only applicable for extension issues) IDE Information

No response

MarcoGorelli avatar May 15 '26 16:05 MarcoGorelli

Hi, I'd like to work on this.

I was able to reproduce the issue from the sandbox. My plan is to add a regression test for isinstance tuple narrowing, then trace where negative narrowing is applied after the first branch and make sure tuple targets like (str, bytes) remove both alternatives from the remaining union.

Could you assign this to me?

LeSingh1 avatar May 15 '26 18:05 LeSingh1

Thanks @LeSingh1! I see that you've already opened a PR; we'll get to it as soon as we can.

rchen152 avatar May 16 '26 22:05 rchen152