0

I need to do a recursive definition inside the class, for example

class Formula:
    root: str
    first: Optional[Formula]
    second: Optional[Formula]
    def __init__(self, root: str, first: Optional[Formula] = None,
             second: Optional[Formula] = None) -> None:

I get the following error : 'unresolved refrence Formula'

Any suggestions would be appreciated.

1 Answer 1

1

Use a string instead of the value itself.

class Formula:
    root: str
    first: 'Optional[Formula]'
    second: 'Optional[Formula]'

or (in Python 3.7 or later) import the annotations future.

from __future__ import annotations

class Formula:
    root: str
    first: Optional[Formula]
    second: Optional[Formula]

See PEP-563 for details. Today, type hints are evaluated as expressions; in the future, starting with Python 4, they will simply be stored unevaluated as strings in __annotations__ attribute of the class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.