pythonmypyrecursive-datastructures

How can two python classes declare references each other and itself?


This is a very basic question that is actually two questions in one. The hopefully very simple answer that exposes my Python greenness is probably the same for both questions.

The following code has two problems:

    #! /usr/bin/python3.10
    
    class A:
       a:A=A()
       b:B=B()
    
    class B:
       a:A=A()
       b:B=B()

I am having type error and want to use mypy. If I create the variables outside of the class declarations as attributes or otherwise hide the desired types, then mypy will not see the type declarations and cannot parse my program for type errors.

Why would I want this, you might ask? Recursive data structures have infinitive applications, but...

Can Python do these very basic things in a manner where mypy can be satisfied with the type declarations?

I am beginning of think that the 'python way' is for every function to type-check every parameter. The more I consider it, the more logical it is for an interpreted language to make such a requirement, but I would still like to keep my code as organized and declarative as possible.


Solution

  • [Answer edited following discussion in the comments.]

    If you want a recursive class definition with an __init__ method, then a proper implementation will depend on your goals, but PirateNinjas's answer using Optional is probably what you want. However, if you really need static class members, you can initialize them after declaring both classes:

    class A:
        a: 'A'
        b: 'B'
    
    class B:
        a: 'A'
        b: 'B'
    
    A.a = A()
    A.b = B()
    B.a = A()
    B.b = B()