python / python/mypy

Regression of os.scandir() typecheck

Open
#11,964 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Type variable inference related with os.scandir() seems to generate false-positives.

To Reproduce

Here is a minimal reproduction example, which is accepted by mypy 0.910 but rejected by 0.930 and 0.931.

from __future__ import annotations

import os
from pathlib import Path


def _calc_usage(target_path: Path | os.DirEntry) -> None:
    with os.scandir(target_path) as scanner:
        for entry in scanner:
            if entry.is_dir():
                _calc_usage(target_path)
            else:
                print('f')


_calc_usage(Path('.'))

Expected Behavior

Success: no issues found in 1 source file

Actual Behavior

test.py:8: error: Value of type variable "AnyStr" of "scandir" cannot be "Union[DirEntry[Any], Any]"

Your Environment

  • Mypy version used: 0.931
  • Mypy command-line flags: python -m mypy test.py
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.9.6
  • Operating system and version: macOS 12.1

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 running the minimal reproduction in test.py with mypy 0.931 and compare it with 0.910. Trace the os.scandir() type-variable inference that produces the AnyStr error, and confirm the fix by rerunning the example with the expected successful result.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.