Core

Core pieces needed to use during code generation.

Data

Out code generator will need a class to hold data while doing code generation. For this reason, the first class we are developing is creatively named Data


Data

 Data (name:str, attrs:Optional[dict[str,Any]]=None)

Data holder used during code generation. Logic is kept as separate functions.

Type Default Details
name str Name of this element
attrs Optional None Attributes for this element
Returns None

Basic operations

Now that we have a class to hold our data, and only for now, we declare structures to use for code generation, manually. Later, we’ll create some data-loaders.

james = Data("person", {"name": "james"})

print(james)

# ---
test_eq(james.name, "person")
test_eq(james.attrs, {"name": "james"})

We can add children (note: a child’s attributes will also include those of his parent)

james = Data("person", {"name": "james"})
olive = james.append(Data("person", {"name": "olive"}))
silva = james.append(Data("person", {"name": "silva"}))

andrew = olive.append(Data("person", {"name": "andrew"}))

john = james.append(Data("person", {"name": "john"}))
jane = olive.append(Data("person", {"name": "jane"}))
noname = olive.append(Data("person"))

# ---
test_eq(james.children[0].attrs["name"], "olive")

and a child will know its parent

print(olive.parent.attrs["name"])

# ---
assert james == olive.parent
# test_eq(james, olive.parent)

To check the number of children, simply use len

len(james)

# ---
assert len(james) == 3

You can compare elements but they are tested based on their attributes and children

b = Data("b", {"age": 22})
c = Data("b", {"age": 22})
d = Data("d")
b.append(d)
c.append(d)

# ---
assert b == c
# test_eq(b, c)
assert Data("b", {"name": "santos"}) == Data("b", {"name": "santos"})
# test_eq(Data("b", {"name": "santos"}), Data("b", {"name": "santos"}))
assert Data("b") != Data("c")
# test_ne(Data("b"), Data("c"))
assert Data("b", {"name": "silva"}) != Data("b", {"name": "santos"})
# test_ne(Data("b", {"name": "silva"}), Data("b", {"name": "santos"}))

You can test if an element is a child of another

test_eq(olive in james, True)

Cloning

You can duplicate any Data instance

james.clone()

Logic

Basic iteration of all the elements

If you just need to iterate through all the elements, a simple loop will suffice

for person, level in james:
    print("   " * level, person.name + "::" + person.attrs["name"])