= Data("person", {"name": "james"})
james
"person")
test_eq(james.name, "name": "james"}) test_eq(james.attrs, {
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
We can add children (note: a child’s attributes will also include those of his parent)
= Data("person", {"name": "james", "root": "true"})
james = Data("person", {"name": "olive"})
olive = Data("person", {"name": "silva"})
silva = Data("person", {"name": "andrew"})
andrew = Data("person", {"name": "john"})
john = Data("person", {"name": "jane"})
jane = Data("person", {"name": ""})
noname
james.append(olive)
james.append(silva)
james.append(john)
olive.append(andrew)
olive.append(jane)
olive.append(noname)
# ---
0].attrs["name"], "olive")
test_eq(james.children["root"], "true") test_eq(jane.attrs[
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
= Data("b", {"age": 22})
b = Data("b", {"age": 22})
c = Data("d")
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
in james, True) test_eq(olive
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"])