Skip to content

Incorrect handling of Self when operating on the different class instance than self #14635

Closed

Description

@AMDmi3

Bug Report

mypy complains on a method returning Self when it returns another instance of its own class.

To Reproduce

from typing import Self
class Foo:
    def spawn(self) -> Self:
        return Foo()

Expected Behavior

The same output as with

class Foo:
    def spawn(self) -> 'Foo':
        return Foo()

Actual Behavior

1.py:4: error: Incompatible return value type (got "Foo", expected "Self")  [return-value]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.0.0 (compiled: no)
  • Mypy command-line flags: -
  • Mypy configuration options from mypy.ini (and other config files): -
  • Python version used: Python 3.11.1

Activity

  1. JelleZijlstra commented on Feb 7, 2023

    @JelleZijlstra
    Member

    This error is correct. Self means that the method will return the same type even in subclasses. Your method does not do that.

  2. johnthagen commented on Feb 8, 2023

    @johnthagen
    Contributor

    Thanks for the explanation @JelleZijlstra.

    While I'm bummed because I was hoping I could fix the forward declaration problem nearly everywhere by applying Self even to normal methods, your explanation about the type theory reasoning makes sense. I guess we'll keep using from __future__ import annotations until PEP 649 lands.

  3. hauntsaninja commented on Feb 8, 2023

    @hauntsaninja
    Collaborator

    Maybe it could be allowed in final classes

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