Python 3.6 types: Using variable before assignment [duplicate] Python 3.6 types: Using variable before assignment [duplicate] python-3.x python-3.x

Python 3.6 types: Using variable before assignment [duplicate]


Forward references are just strings referring to the name (as it is visible in the module).

class MyContainer:    def addMyItem(self, item: 'MyItem'):        passclass MyItem:    def __init__(self, container: 'MyContainer'):        pass

If you need to import the name from somewhere else (and you only need the name for type checking, or if it might cause a circular import), you can use

import typingif typing.TYPE_CHECKING:    from foo import Thing

TYPE_CHECKING is true only when a type checker is running (i.e. your code is not being evaluated for execution).