Home > Enterprise >  How to type hint a method that returns a subclass?
How to type hint a method that returns a subclass?

Time:02-01

I have the setup

import typing

class A:
    def get_b(self) -> B: # <- ERROR: B is not defined yet
       return b # <- and instance of B here

class B(A): # <- subclass of A, defined after A is defined
    pass 

Is there a clean way to type hint the method get_b?

Edit: thanks to the wonderful answers, this problem is not really addressed in the documentation, but in some PEPs, one of them is the problem of forward declarations

CodePudding user response:

You can put B in quotes like:

class A:
    def get_b(self) -> 'B':
       return b

class B(A):
    pass 
  • Related