-
Consider this code:
I get pylance underlying in red the last line of the code of the add method, and when I move the mouse over it, I get the following message: However, if I try to run the code, I encounter no errors. Also, if I open the same code with PyCharm, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Pyright (the type checker that underlies pylance) is working correctly here and in conformance with the Python typing spec. If you'd like to read more about the When you use Note that your You can fix your code in one of two ways here:
def __add__(self, other: Self) -> "Book":
return type(self)(combined_title, combined_pages) or return self.__class__(combined_title, combined_pages) |
Beta Was this translation helpful? Give feedback.
Pyright (the type checker that underlies pylance) is working correctly here and in conformance with the Python typing spec. If you'd like to read more about the
Self
type and how the typing spec defines it, refer to this link.When you use
Self
in a type annotation, it represents an implicit type variable scoped to the class in which it is contained and with an upper bound of that class. It is meant to be used in cases where the class may be subclassed, and it's a stand-in for whatever subclass is used for a given instance. For example, if you created a subclass ofBook
calledNovel
, theSelf
type variable would concretely be of typeNovel
if you were to instantiate aNovel
object.Note t…