Skip to content

Unable to use Self as return type of normal method #14649

Closed as not planned
Closed as not planned

Description

@johnthagen

Bug Report

Using Self on a normal method leads to a type error.

To Reproduce

from dataclasses import dataclass
from typing_extensions import Self

@dataclass(frozen=True)
class Point:
    x: int
    y: int

    def subtract(self, x: int, y: int) -> Self:
        return Point(x=self.x - x, y=self.y - y)

print(Point(x=10, y=10).subtract(1, 1))

Expected Behavior

Expected this to type check. We have been looking to use Self to remove all cases of the forward reference problem and avoid using from __future__ import annotations, which looks like it will be deprecated eventually.

It seems like Self should coalesce to the same type in this instance?

Actual Behavior

mypy --strict main.py
main.py:12: error: Incompatible return value type (got "Point", expected "Self")  [return-value]
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): N/A
  • Python version used: 3.10.8

Activity

  1. hauntsaninja commented on Feb 8, 2023

    @hauntsaninja
    Collaborator

    Mypy is correct here, see #14635

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-self-typesTypes for self

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions