Proposal for new operators to python that add syntactic sugar for hierarcical data.

Diez B. Roggisch deets at nospam.web.de
Thu May 18 00:07:58 CEST 2006


glomde schrieb:
> i I would like to extend python so that you could create hiercical
> tree structures (XML, HTML etc) easier and that resulting code would be
> more readable than how you write today with packages like elementtree
> and xist.
> I dont want to replace the packages but the packages could be used with
> the
> new operators and the resulting IMHO is much more readable.
> 
> The syntax i would like is something like the below:
> 
> # Example creating html tree
> 
> '*!*' is an operator that creates an new node,
> '*=*' is an operator that sets an attribute.
> 
> So if you take an example to build a smalle web page
> and compare with how it looks with in element tree now
> and how it would look like when the abover operators would exist.
> 
> With element tree package.
> 
>   # build a tree structure
>   root = ET.Element("html")
>   head = ET.SubElement(root, "head")
>   title = ET.SubElement(head, "title")
>   title.text = "Page Title"
>   body = ET.SubElement(root, "body")
>   body.set("bgcolor", "#ffffff")
>   body.text = "Hello, World!"
> 
> 
> 
> With syntactical sugar:
> 
>   # build a tree structure
>   root = ET.Element("html")
>   *!*root:
>      *!*head("head"):
>          *!*title("title):
>               *=*text = "Page Title"
>      *!*body("body"):
>               *=*bgcolor = "#ffffff"
>               *=*text = "Hello, World!"
> 
> 
> 
> I think that with the added syntax you get better view of the html
> page.
> Repeating things dissapears and you get indentation that corresponds to
> the tree.
> I think it is very pythonic IMHO.
> 
> It could be done quite generic. If  the variable, object after '*!*'
> must support append
> method and if you use  '*=*' it must support __setitem__
> 
> Any comments?

It's ugly, and could easily achieved using the built-in tupels, lists 
and dictionaries together with a simple traversing function.

Like this (untested):

class Node(object):
    def __init__(self, value):
        self.value = vallue
        self._childs = []
    def append(self, child):
        self._childs.append(child)


t = ('root',
      ('child1,
        ('grandchild', ()),
       'child2',
        ()
      )
     )

def create_node(t):
     value, childs = t
     n = Node(value)
     if childs:
        for ch in childs:
           n.append(create_node(ch))
     return n


IMHO that tuple-based tree is waaay more readable than your proposal - 
and no need to come up with new syntax.

Diez



More information about the Python-list mailing list