You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
typing.Self should be used where a class method returns an instance of the class. If the class method delegates to a function that has an explicit return type then mypy reports an error for the use of self.
To Reproduce
This Python code in "test.py":
from typing import Self
class Thing:
@classmethod
def constructor(cls) -> Self:
return function()
def function() -> Thing:
return Thing()
Expected Behavior
No Errors
Actual Behavior
Produces this report from mypy:
$ mypy test.py
test.py:8: error: Incompatible return value type (got "Thing", expected "Self") [return-value]
Your Environment
Mypy version used:
$ mypy --version
mypy 1.13.0 (compiled: yes)
Python 3.12, Ubuntu 24.04
The text was updated successfully, but these errors were encountered:
Mypy is correct to report an error here. Self isn't equivalent to the type of current class. Rather, it works like a type variable with an upper bound of the current class. Returning a Thing from a function with a return type of Self isn't allowed, since that would be invalid in cases where Self gets bound to a subtype of Thing. Consider:
classSubThing(Thing):
deffoo():
pass# Here, 'Self' is bound to 'SubThing', so 'x' has type 'SubThing'x=SubThing.constructor()
# The type system says this should be ok...x.foo() # boom! AttributeError: 'Thing' object has no attribute 'foo'
See also Generic - Self from the typing spec for more details on how Self works.
You're right, the code plays terribly with subclasses. (It's from an example for a course.) I've moved the code into the method and am using cls() instead of the hardcoded type in the function. Much better. I was surprised it didn't work though - thanks for the explanation.
Bug Report
typing.Self should be used where a class method returns an instance of the class. If the class method delegates to a function that has an explicit return type then mypy reports an error for the use of self.
To Reproduce
This Python code in "test.py":
Expected Behavior
No Errors
Actual Behavior
Produces this report from mypy:
Your Environment
Python 3.12, Ubuntu 24.04
The text was updated successfully, but these errors were encountered: