Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

typing.Self does not work properly with class variables #16410

Closed
McDic opened this issue Nov 5, 2023 · 1 comment · Fixed by #17381
Closed

typing.Self does not work properly with class variables #16410

McDic opened this issue Nov 5, 2023 · 1 comment · Fixed by #17381
Labels
bug mypy got something wrong topic-self-types Types for self

Comments

@McDic
Copy link

McDic commented Nov 5, 2023

Bug Report

typing.Self does not work well with class variables.

To Reproduce

In Python 3.11, write and execute the same code from here, which is

import math
import typing


class Team:
    """
    Represent "team" in Minecraft.
    """

    _cache: dict[str, typing.Self] = {}

    def __init__(self, name: str):
        self._name = name
        if self._name in type(self)._cache:
            raise ValueError('Team "%s" already exists;' % (self._name,))
        else:
            type(self)._cache[self._name] = self

    @property
    def name(self):
        return self._name

    @classmethod
    def get_team(cls, name: str) -> typing.Self:
        """
        Use this method to create a team instead of calling constructor directly.
        """
        if name in cls._cache:
            return cls._cache[name]
        else:
            return cls(name)

Expected Behavior

There should be no error.

Actual Behavior

Mypy reports Incompatible return value type (got "Team", expected "Self") on return cls._cache[name].

Your Environment

  • Mypy version used: 1.1.6
  • Mypy command-line flags: mypy (filename)
  • Mypy configuration options from mypy.ini (and other config files): Nothing
  • Python version used: 3.11.6
@McDic McDic added the bug mypy got something wrong label Nov 5, 2023
@AlexWaygood AlexWaygood added the topic-self-types Types for self label Nov 5, 2023
@cossor
Copy link

cossor commented Nov 11, 2023

i think this is a minor issue, so i'm commenting only because i think we should minimize quoted string usage in type hints.

mypy 1.7.0 (Python 3.12) also emits a return-value complaint after checking a smaller example:

import typing


class Spam:
    @classmethod
    def instance(cls) -> typing.Self:
        return Eggs()


class Eggs(Spam):
    pass

in the first example, cls might not be Self so my example doesn't really change anything?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-self-types Types for self
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants