breaking expectations

How do you thing, what the following Python/libxml2 code does?

for kid in node.get_children():
  print kid.name

Do you think the code gets the children of the node and prints theirs names? I thought so too. But the correct answer is:

The code gets all the ancestors of the node and prints theirs names.

In libxml2, get_children() returns a pointer to the first child. By the way, for C it's very reasonable and expected. Being only a wrapper, Python shouldn't change the behaviour. It's reasonable. Further, Python's xmlNode provides an interator which traverses the whole subtree of the mode.

This is an excellent example how reasonable steps lead to a misfeature.

My implementation of getting all the children:

def getChildren(node):
  kids = []
  kid  = node.get_children()
  while kid:
    kids.append(kid)
    kid = kid.get_next()
  return kids
Categories: python

Updated: