'Python Type Hint for parent class function that returns same type as calling class?

Is there a way to type hint a parent class function to show that it returns the same type as the actual calling class?

Consider this:

  • class B inherits from class A and implements a function func_b
  • class A has a function func_a that returns whatever type is passed in
  • An instance of class B, “b”, calls func_a as follows: b2 = b.func_a()
  • Is there a way to typehint func_a (or something else) so that the IDE sees b2.func_b() as a valid call?

'''

import __future__

class A:
    def func_a(self) -> "A":
        return self
class B(A):
    def func_b(self) -> None:
        print("func_b was called")
a = A()
a.func_a()
b = B()
b2 = b.func_a()
b2.func_a()
# IDE doesn't recognize that b2 is of class B and so b2.func_b() is white not yellow
# but still works
b2.func_b()

'''

func_b() is white rather than yellow: func_b() is white rather than yellow



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source