Narrowing IO[str] | None with sys.stdout is still considered possibly None
- Dominant language
- Python
- Stars
- 15.6k
- Forks
- 1.8k
- Avg merge
- 12h 13m
- Merged PRs (30d)
- 52
Description
**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.
```python
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 informations
```
outfile cannot be None on line 8.
Contributor guide
Research direction
Start with the minimal Python reproducer in the issue and run it against pyright 1.1.414, checking the revealed types for sys.stdout and outfile. Trace how the checker narrows `outfile = outfile or sys.stdout`; done means the resulting outfile is no longer reported as possibly None and the write call produces no error.
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
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 68/100