python / python/mypy

Attrs plugin mishandles typing.Self in generated inits

Open
#14,685 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

MyPy mishandles type comparisons when an argument in an attrs generated init uses typing.Self.

To Reproduce

import attrs
import typing

from typing_extensions import Self


@attrs.define()
class Dataclass:
    child: typing.Optional[Self] = None


Dataclass(child=Dataclass())

Expected Behavior

The attrs version of this code should pass type checking like MyPy does with the following dataclasses and normal init examples

import typing

import dataclasses
from typing_extensions import Self


@dataclasses.dataclass
class Dataclass:
    child: typing.Optional[Self] = None


Dataclass(child=Dataclass())
import typing

from typing_extensions import Self


class Dataclass:
    def __init__(self, child: typing.Optional[Self] = None) -> None:
        self.child = child
    

Dataclass(child=Dataclass())

Actual Behavior

MyPy false-positive reports an incompatible type for the argument only when using attrs

test.py:12: error: Argument "child" to "Dataclass" has incompatible type "Dataclass"; expected "Optional[Self]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.0.0
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.10.9
  • Attrs version used: 22.2.0

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 provided attrs reproduction with MyPy 1.0.0 and --strict, then trace how the attrs plugin handles generated init arguments involving typing.Self. Compare the result with the dataclass and normal-init examples; done means the attrs example passes type checking without the incompatible-type error.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.