Hi! I’m trying to access the previous dataclass in the second dataclass, both nested in a dataclass. How to solve this error?
from dataclasses import dataclass
@dataclass
class Grammar:
@dataclass
class T:
BLOCK_OPEN = "a"
@dataclass
class EX:
CODE_BLOCK = T.BLOCK_OPEN + "b" # "T" is not defined
Hi! I’m defining a custom grammar for my DSL (domain specific language) and I want to access it by using Grammar.T. for tokens and Grammar.EX. for expressions. In the simplified example above the tokens and expressions are just strings, but in my real code I use import pyparsing as pp, so for example Grammar.T.BLOCK_OPEN is a pp.Literal("${{") object.
from dataclasses import dataclass
@dataclass
class _T:
BLOCK_OPEN = "a"
@dataclass
class _EX:
CODE_BLOCK = _T.BLOCK_OPEN + "b"
@dataclass
class Grammar:
T = _T
EX = _EX
I’d go with that one. The original design is difficult to understand, when considering the question “What do you want to happen to T and EX, on an instance of Grammar?”
In general when composing objects, or creating tree structures, to let nodes at the same level access each other, a composed/downstream node needs to be given a reference to its owning instance/upstream node. It can access nodes at the same level as itself from there. A parent/children/sibling analogy could be used to describe it too, but I wanted to avoid confusion with inheritance.