Skip to content

Attrs plugin mishandles typing.Self in generated inits #14685

Open

Description

@FasterSpeeding

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

Activity

  1. changed the title [-]Attrs plugin mishandles typing.Self in generated inits.[/-] [+]Attrs plugin mishandles typing.Self in generated inits[/+] on Feb 12, 2023
  2. PhilReinhold commented on Feb 15, 2023

    @PhilReinhold

    I think this is related to the similar problem I was experiencing:

    from typing_extensions import Self
    
    class A:
        def __init__(self) -> None:
            self.related: list[Self] = []
    
        def copy(self) -> Self:
            raise NotImplementedError
    
        def add_related(self) -> None:
            self.related.append(self.copy())

    which when ran through mypy 1.0.0 gives

    test.py:11: error: Argument 1 to "append" of "list" has incompatible type "A"; expected "Self"  [arg-type]
    
  3. davfsa commented on Feb 16, 2023

    @davfsa
    Contributor

    I think this is related to the similar problem I was experiencing:

    @PhilReinhold nope, that seems to be similar to #14685, which I have opened a pr (#14712) to try and fix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions