Please consider the following working code
from __future__ import annotations
class A(object):
def __init__(self, val: int):
self.val = val
@property
def b(self) -> B:
return B(self)
class B(object):
def __init__(self, a: A):
self.a = a
a = A(val=1)
print(a.b.a.val)
Which only works when both classes are defined within the same file.
output: 1
I want to put each class in a different file, and doing it like so:
file uv_dataset.cvbnhxx.b2
:
from uv_dataset.cvbnhxx.a2 import A
class B(object):
def __init__(self, a: A):
self.a = a
file uv_dataset.cvbnhxx.a2
:
from uv_dataset.cvbnhxx.b2 import B
class A(object):
def __init__(self, val: int):
self.val = val
@property
def b(self) -> B:
return B(self)
a = A(val=1)
print(a.b.a.val)
now gives
ImportError: cannot import name 'B' from partially initialized module 'uv_dataset.cvbnhxx.b2' (most likely due to a circular import) (/home/noam.s/src/uv_metadata/uv_dataset/cvbnhxx/b2.py)
How to make circular annotations resolve properly? I was not able to do it correctly with forward declaration, but likely because I got the syntax wrong.
This answer doesn't work for multiple files.