Search code examples
pythonprototypejs

Prototype for python?


I just learned Prototype for Javascript. It's super convenient: using the $ shortcut, accessing xml elements is not painful any more!

The question: is there a Prototype-like extension for Python?


Solution

  • Python has lxml which has the xpath method wherein you could use xpath expressions to select elements. As I understand it, $ in prototype searches and returns an element that has a particular id, in which case could be translated in xpath to *[@id=<someid>] like so:

    >>> import lxml.etree
    >>> tree = lxml.etree.XML("<root><a id='1'/><b id='2'/></root>")
    >>> tree.xpath("*[@id=1]")
    [<Element a at c3bc30>]
    >>> lxml.etree.tostring(tree.xpath("*[@id=1]")[0])
    '<a id="1"/>'
    

    I think the Python standard library includes support for a subset of xpath in ElementTree too so you might be able to implement that there somehow if you do not wish to install lxml (which isn't included in stdlib)...