Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 963
Cauly Avatar asked Jun 21 '26 00:06

Cauly


1 Answers

You can pass the first reference as a string (Python 3.5+):

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

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

It's called "forward reference" and was laid out in PEP484. See this answer for more ways and detailed information.

like image 187
lorey Avatar answered Jun 23 '26 02:06

lorey