Title: How to specify an instance with a subclass without typing hint errors?
Tags: python;mypy
Question: I'm using instance __class__ attribute to specify an instance created from the super class. But MyPy rejects it with Incompatible return value type.
Is there a most pythonic option to do that without ignoring it?
Here is my example code:
class A:
def __init__(self, a: int = None):
self.a = a or 1
class B(A):
def b(self) -&gt; int:
return 5 + self.a
@classmethod
def specify(cls, a_instance: A) -&gt; 'B':
a_instance.__class__ = cls
return a_instance  # type: ignore
if __name__ == &quot;__main__&quot;:
s = A(6)
s = B.specify(s)
print(s.b())
and the error if you don't ignore typing:
% mypy scratch_7.py
scratch_7.py:13: error: Incompatible return value type (got &quot;A&quot;, expected &quot;B&quot;)
Found 1 error in 1 file (checked 1 source file)
Comment: @ARMAN there is not any Traceback on this error. It's just a typing error message. It runs ok.

Comment: add full error Trackback here

Here is the accepted answer: mypy supports dynamically type casting with the use of typing.cast.
from typing import cast
class B(A):
def b(self) -&gt; int:
return 5 + self.a
@classmethod
def specify(cls, a_instance: A) -&gt; 'B':
a_instance.__class__ = cls
a_instance = cast('B', a_instance)
return a_instance
# Success: no issues found in 1 source file
typing.cast doesn't change the value, it only signals the type checker (mypy) that the type has changed.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:10/24/21', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><mypy>', 'Title': 'How to specify an instance with a subclass without typing hint errors?', 'ViewCount': 49, 'id': 69697457, 'user_AboutMe': "<p>I'm an usual developer with a lot of interestings :-)</p>\n", 'user_AccountId': 2474045.0, 'user_DisplayName': 'Cristian S. Rocha', 'user_Reputation': 113.0, 'user_Views': 10.0, 'user_id': 2155091.0}}