Search code examples
pythonpython-typing

How to use a type defined later for function annotations?


The problem is like this:

class A():
    def foo() -> B:
        pass

class B():
    def bar() -> A:
        pass

This will raise a NameError: name 'B' is not defined.

For the sake of type checking, I'm not willing to change -> B to -> "B". Is there any workaround?


Solution

  • I found a workaround, which is much similar to C or C++.

    Tested in Pycharm 3.

    class A: pass
    class B: pass
    
    class A(object):
    
        def foo(self, b: B) -> B:
    
            #CAN auto complete
            b.bar()
    
            return B()
    
    class B(object):
    
        def bar(self) -> A:
    
            return A()
    
    #CAN auto complete
    A().foo(B()).bar()