python / python/mypy

Issues with solving value constrained type var in presence of Any

Open
#17,952 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

In 1.11.0, classes that inherit from os.PathLike could be used with os.path methods. As of 3.12, these methods claim to accept "any object implementing the os.PathLike protocol". However, in 1.12.0, mypy emits an error.

To Reproduce

import os


class MyPath(os.PathLike):
    def __init__(self, path: str):
        super().__init__()
        self.path = path

    def __fspath__(self):
        return self.path


print(os.path.abspath(MyPath(".")))

Expected Behavior

Unless I'm missing something, MyPath should be valid to pass, no?

Actual Behavior

pathlike.py:13: error: Value of type variable "AnyStr" of "abspath" cannot be "MyPath | Any"

Your Environment

  • Mypy version used: 1.12.0
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12

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 with the provided Python reproducer using os.PathLike, os.path.abspath, and the MyPath class, and compare behavior between mypy 1.11.0 and 1.12.0 on Python 3.12. Trace how the type checker handles the constrained AnyStr type variable when MyPath and Any are involved; done means the reproducer type-checks without the reported error while preserving valid diagnostics.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.