A horrible little ElementTree gotcha

What does this print:

from lxml import etree
doc = etree.fromstring('<a><b><c/></b></a>')
newdoc = etree.ElementTree(doc.find('b'))
print newdoc.xpath('/b/c')[0].xpath('/a')

The answer is: [<Element a at 817548c>]. The first point to note is that xpath() against an element is only relative to that element: any absolute XPaths enumerate from the top of the containing tree. The second point is that the shallow copying of etree means that _Element::xpath, unlike _ElementTree::xpath, evaluates absolute paths from the top of the original underlying tree! So even though there's no <a> in newdoc, an absolute XPath on a child element can still reach it.


YouTube annoyance

How much time would it really take to order multi-part videos, so the suggestion at the end of the video is the next part? Please!


An annoying Python gotcha

Imagine you have this in mod.py:

import foo

class bar(object):

def __del__(self):

Seems fine right? In fact, there's a nasty bug here. If I try to use this module in client.py like so:

import mod
mybar = bar()

Then you're likely to get an exception when the program exits. This is because Python, for some bizarre reason, Nones out the globals in mod.py when taking down the interpreter. The actual __del__ method can be called sometime after this, and it ends up trying None.cleanup(), with the resultant AttributeError. It seems extremely bizarre that it happens in this order, but it does (a real example).