Skip to content

[arg-type] "Argument has incompatible type" for TypeVar bound to Union passed to overloaded function #18075

@Avasam

Description

@Avasam

Bug Report

If I try to pass a TypeVar bound to a union to a function that overloads for both part of the union, I get a [arg-type] error. But if I pass the same union not as a TypeVar, it works.

Note that pyright has similar behaviour here.

To Reproduce

import os
from typing import TypeVar, Union
from typing_extensions import TypeAlias, reveal_type

_StrPathT = TypeVar("_StrPathT", bound=Union[str, os.PathLike[str]])
_StrPath: TypeAlias = Union[str, os.PathLike[str]]

def foo(file_path: _StrPathT) -> _StrPathT:
    # Mypy:
    # Argument 1 to "dirname" has incompatible type "_StrPathT"; expected "PathLike[str]" [arg-type]
    # Revealed type is "builtins.str"
    # Pyright:
    # No overloads for "dirname" match the provided arguments [reportCallIssue]
    #   posixpath.pyi(88, 5): Overload 2 is the closest match
    # Argument of type "_StrPathT@foo" cannot be assigned to parameter "p" of type "AnyOrLiteralStr@dirname" in function "dirname"
    #   Type "_StrPathT@foo" is not assignable to constrained type variable "AnyOrLiteralStr" [reportArgumentType]
    # Type of "os.path.dirname(file_path)" is "Unknown"
    reveal_type(os.path.dirname(file_path))
    return file_path

def bar(file_path: _StrPath) -> _StrPath:
    # OK, both reveal type as str
    reveal_type(os.path.dirname(file_path))
    return file_path

Expected Behavior

This feels like a bug but I'm not completely certain. If I split the possible types _StrPathT = TypeVar("_StrPathT", str, os.PathLike[str]) it works, but then my method becomes incorrectly typed as it no longer accepts a str | os.PathLike[str]

Actual Behavior
See comments in MRE

Your Environment

  • Mypy version used: mypy 1.13.0 (compiled: yes)
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): (I've replicated this issue with an empty config file)
  • Python version used: 3.9.13

(I searched for similar issues and only found #13596)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions