ARTICLE AD BOX
I have the following code:
import json from typing_extensions import Any import lz4.block bytebuf = bytes | bytearray MAGIC_HEADER = b"mozLz40\0" def jsonlz4_loads(buf: str | bytebuf) -> Any: if isinstance(buf, bytebuf): header: bytes = MAGIC_HEADER else: header: str = MAGIC_HEADER.decode("ascii") if not buf.startswith(header): raise ValueError("Not a valid JSONLZ4 buffer - magic bytes missing") return json.loads(lz4.block.decompress(buf[len(header):]))When trying to typecheck it, I get errors about incompatible argument types for buf.startswith():
jsonlz4.py:18:27: error[invalid-argument-type] Argument to bound method `startswith` is incorrect: Expected `str | tuple[str, ...]`, found `Literal[b"mozLz40\x00"] | str` jsonlz4.py:18:27: error[invalid-argument-type] Argument to bound method `startswith` is incorrect: Expected `Buffer | tuple[Buffer, ...]`, found `Literal[b"mozLz40\x00"] | str` jsonlz4.py:18:27: error[invalid-argument-type] Argument to bound method `startswith` is incorrect: Expected `Buffer | tuple[Buffer, ...]`, found `Literal[b"mozLz40\x00"] | str`I'm using astral's ty as the typechecker, but I've also tried all the other popular typecheckers (pyright, pyrefly, mypy), and they all report some variation of the above. This confuses me, because I expected the isinstance(buf, bytebuf) to narrow the type sufficiently, but clearly I'm missing something here.
How do I make it typecheck successfully without just marking as # type: ignore?
