Accessing the previous dataclass in the second dataclass, both nested in a dataclass

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

What do you expect to achieve by nesting them in the first?

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.

If it’s not possible then I think I’ll just do:

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

But having it nested looks cleaner to me.

And I think I don’t need to use dataclass in my case :sweat_smile:

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.

Thank you for your time and for your help! I ended up with a structure like this:

class _T:
    BLOCK_OPEN = "a"


class _EX:
    CODE_BLOCK = _T.BLOCK_OPEN + "b"


class Grammar:
    T = _T
    EX = _EX
1 Like