Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cyclic Type Annotations do not work #482

Open
JohnSmith20211124 opened this issue Sep 12, 2023 · 2 comments
Open

Cyclic Type Annotations do not work #482

JohnSmith20211124 opened this issue Sep 12, 2023 · 2 comments
Assignees
Labels
enhancement New feature or request

Comments

@JohnSmith20211124
Copy link

The following code does not compile:

class A:
    b: 'B'
    
class B:
    a: A

Error Message:

error: expected type expression

Even if you omit the quotes around the B it does not work.

@elisbyberi
Copy link

@JohnSmith20211124 The issue you're encountering is due to a circular dependency between classes A and B. In Python, when you define a class attribute that depends on another class that hasn't been defined yet, you'll encounter a NameError because Python doesn't know about B when it's encountered in the definition of class A, and vice versa. You can use forward declarations to tell Python that a class exists without defining its attributes until later in the code. Another way to handle this is to use string names for the classes and then resolve the actual class objects later. Neither of these approaches works in Codon.

class A:
    b: 'B'

class B:
    a: A

i482.py:2:8-11: error: expected type expression
As the error message explains, you need to define a type expression, not a string.

class A:
    b: B

class B:
    a: A

i482.py:2:8-9: error: name 'B' is not defined
That's because the Codon global scope is parsed from top to bottom.

@arshajii
Copy link
Contributor

Hi @JohnSmith20211124 -- we'll be adding support for this soon, but currently you can do this by making the first class generic:

class A[T]:
    b: Optional[T]  # probably want optional if field can be None

class B:
    a: Optional[A[B]]

x = A(B(A(B(None))))

@inumanag inumanag self-assigned this Jan 29, 2024
@inumanag inumanag added the enhancement New feature or request label Jan 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

4 participants