Incompatible types detected in assignment of self
to target of type Self
, when using Self
only in method body
#14708
Labels
self
to target of type Self
, when using Self
only in method body
#14708
Bug Report
When assigning
self
to a list element, where the list is of typelist[Self]
, mypy will treatself
to be incompatible withSelf
as long asSelf
does not appear in the method signature.To Reproduce
Playground: https://mypy-play.net/?mypy=latest&python=3.11&gist=124fa26ca946c7ae040c43d788a694cb
Expected Behavior
self
to a target of typeSelf
should obviously work (or am I missing something here?)self
to beSelf
should not change the behaviorActual Behavior
Mypy detects imcompatible assignments:
Maybe it's actually undefined behavior?
Digging deeper, it looks like PEP 673 lists examples of what are valid or invalid use cases of the
Self
type. It explicitly states thatThis definition would not cover my example above, as it does only fail if
Self
has been used in only the body, but not the signature. On the other hand, this case is listed neither as a positive or negative use case; it is not covered at all by PEP 673, but all examples show that the intention of PEP 673 was to avoid having to explicitly state a signature ofself: Self
, as that would state the obvious.Thus, considering PEP 673, it might be undefined behavior?
On the other hand, following PEP 484:
I guess that's the old definition and does not include how to apply
Self
. It would explain mypy behavior - at least to some end. If this were the explanation, then mypy should actually fail or at least warn about incorrect usage ofSelf
in__init__
andlocal_variable
. WithSelf
being treated as a special case if and only if it appears in method signatures, it does not make sense to use it at those places; at least I cannot think of a use case. I do believe that it is not intended to be used on its own. Thus, an explicit warning, or even an error, would be very helpful in this case.So is this a bug in mypy or is it something that actually simply strictly follows PEP definition? In the second case, I would still consider my example code to be desirable behavior and would be happy to get some hints on how to make this behavior become part of python typing definitions :)
Or if you would think that this would not be desirable, i'd be happy to learn about your rationale.
Your Environment
mypy.ini
(and other config files): installed mypy in a fresh virtualenv, no manual configurationThe text was updated successfully, but these errors were encountered: