johnIsReturned99
johnIsReturned99

Reputation: 1

recursive definiton of class [python]

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.

Upvotes: 0

Views: 50

Answers (1)

chepner
chepner

Reputation: 531165

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.

Upvotes: 1

Related Questions