Description
Bug Report
In methods where the Self
type (from typing
) is used, the Self
type from is considered as distinct to the actual self type (say, Foo
). This is the cause of a multitude of issues.
To exemplify these issues, I will use enum.Enum
s. as they have a clear reason to need access to the runtime self type.
In a method returning Self
, one may not return Foo.Variant
, receiving an error along the lines of:
file.py:#: error: Incompatible return value type (got "Foo", expected "Self") [return-value]
To work around this, one must use typing.cast
or # type: ignore
comments.
Furthermore, within those same methods returning Self
, the self
parameter auto-magically assumes the type of Self
, to accommodate the fact that Self
is seen by mypy as a TypeVar
and "A function returning TypeVar should receive at least one argument containing the same TypeVar [type-var]".
This brings on the unfortunate consequence that one cannot match the self
value against its own enum variants exhaustively, mypy simply refuses to acknowledge that self
may take on values of Foo.Variant
. Trying to access the fields through the self parameter as self.Variant
reveals that it indeed has the type auto
(or whichever value was assigned to it), rather than the literal or the class.
To Reproduce
https://mypy-play.net/?mypy=latest&python=3.11&flags=strict&gist=808ead69249e64d6929a55149b0a3f1c
Actual Behavior
For the above example, the errors include:
main.py:35: error: Missing return statement [return]
main.py:37: error: Incompatible return value type (got "Dir", expected "Self") [return-value]
main.py:38: error: Incompatible return value type (got "Dir", expected "Self") [return-value]
main.py:39: error: Incompatible return value type (got "Dir", expected "Self") [return-value]
main.py:40: error: Incompatible return value type (got "Dir", expected "Self") [return-value]
Environment
- Mypy version used: master (
1.8.0+dev.5b1a231425ac807b7118aac6a68b633949412a36
) - Mypy command-line flags:
--strict
- Mypy configuration options from
mypy.ini
(and other config files):strict = True
- Python version used:
3.11.5