python / python/mypy

Overloaded `__init__` prevents type from being recognized as an attrs class

Open
#19,003 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

When an attrs class has and overloaded __init__ function, mypy does not consider it to be an attrs class when evaluating attrs.evolve.

To Reproduce

from typing import overload

import attrs


@attrs.frozen(init=False)
class C:
    x: int | str

    @overload
    def __init__(self, x: int) -> None: ...

    @overload
    def __init__(self, x: str) -> None: ...

    def __init__(self, x: int | str) -> None:
        self.__attrs_init__(x)


obj = C(1)
attrs.evolve(obj, x=2)  # error

Expected Behavior

The C instance should be an acceptable input to attrs.evolve.

Actual Behavior

$ mypy t.py
t.py:21: error: Argument 1 to "evolve" has incompatible type "C"; expected an attrs class  [misc]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.15.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: Python 3.13.0 (v3.13.0:60403a5409f, Oct 7 2024, 00:37:40) [Clang 15.0.0 (clang-1500.3.9.4)]

Notes

This appears to be because the init method is both not a FuncDef (it is OverloadedFuncDef) and its type attribute is not a CallableType. See: https://github.com/python/mypy/blob/7b4f6311e29452cc8d4ddb78331d0047c8b17e93/mypy/plugins/attrs.py#L1033-L1034

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 at mypy/plugins/attrs.py around lines 1033-1034 and reproduce the issue with the provided overloaded-init snippet using mypy 1.15.0. The work is done when attrs.evolve accepts the C instance without the reported incompatible-type 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
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.