KEMBAR78
Metaclass Usage Example Code Incorrect · Issue #18668 · python/mypy · GitHub
Skip to content

Metaclass Usage Example Code Incorrect #18668

@Geo5

Description

@Geo5

Documentation
The Metaclasses usage example code seems to be incorrect: https://mypy.readthedocs.io/en/stable/metaclasses.html#metaclass-usage-example
If check the given code snippet:

from typing import ClassVar, Self

class M(type):
    count: ClassVar[int] = 0

    def make(cls) -> Self:
        M.count += 1
        return cls()

I get:

$ mypy --strict test.py
test.py:7: error: Self type cannot be used in a metaclass  [misc]
test.py:9: error: Returning Any from function declared to return "Self"  [no-any-return]
Found 2 errors in 1 file (checked 1 source file)

I think the second error is a consequence of the first. The relevant PEP 673 mentions Self is not allowed in a metaclass:
https://peps.python.org/pep-0673/#valid-locations-for-self


$ python --version
Python 3.11.10
$ mypy --version
mypy 1.15.0 (compiled: yes)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions