Narrowing IO[str] | None with sys.stdout is still considered possibly None
Author: nedbatCreated Sep 15, 2026Updated Sep 15, 2026
Labelsas designed
Describe the bug A clear and concise description of the behavior you are seeing and the expected behavior along with steps to reproduce it.
Code or Screenshots If possible, provide a minimal, self-contained code sample (surrounded by triple back ticks) to demonstrate the issue. The code should define or import all referenced symbols.
import sys
from typing import IO, reveal_type
def report(outfile: IO[str] | None = None) -> None:
reveal_type(sys.stdout)
outfile = outfile or sys.stdout
reveal_type(outfile)
outfile.write("Hello")This produces (with pyright 1.1.414):
/Users/nbatchelder/n/coveragepy/prbug.py
/Users/nbatchelder/n/coveragepy/prbug.py:5:17 - information: Type of "sys.stdout" is "TextIO | Any"
/Users/nbatchelder/n/coveragepy/prbug.py:7:17 - information: Type of "outfile" is "IO[str] | TextIO | None"
/Users/nbatchelder/n/coveragepy/prbug.py:8:13 - error: "write" is not a known attribute of "None" (reportOptionalMemberAccess)
1 error, 0 warnings, 2 informationsoutfile cannot be None on line 8.
Source: microsoft/pyright