3
votes

Well 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.

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


For further discussion, I really can't see any point in an annotation like "def foo(a: 'x', b: 5 + 6, c: list) -> max(2, 9):" (IN PEP 3107). Why the hell python threat these annotations for expression?

2
the parameter annotations is a good way to document your code it also helps the ide to "know" what type you are expecting so it does the code completion for you. - Foo Bar User

2 Answers

2
votes

I found a workaround, which is much similar to c/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()
0
votes

Well, there is no way to directly do it using the annotation syntax, but one can modify the __annotations__ dictionary of a function object.

class A():
    def foo():
        pass

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

A.foo.__annotations__["return"] = B