Skip to content

Python type hinting passed parent references without circular import error

Louis Maddox edited this page Jul 3, 2021 · 1 revision

An example of passing a reference to a "parent" when creating a new instance of a class session.py without creating a circular import from importing the class of the 'parent' (which of course has to import the 'child' for its code which involves creating it) relies on the typing module's constant TYPE_CHECKING which is True for type checkers like mypy and False for running the Python program normally.

This allows a conditional import (terrible hack, but the best you can get apparently). Also requires from __future__ import annotations if running versions before Python 3.10.

In session.py you have:

import response


class Session:
    def __repr__(self):
        return f"Session"

    def request(self, url: str):
        self.response = response.Response(self, url)

and response.py:

from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import session


class Response:
    def __init__(self, session: session.Session, url: str):
        self.parent_session = session
Clone this wiki locally