Simply Jonathan

This is Simply Jonathan, online writing habitat for Jonathan Holst. In here, you may find content divided into three main categories: links, notes and essays. The links are to external content of interest; the notes are small thoughts and ponderings; the essays are longer, more thought-through entries, often debating a subject thoroughly. Read more about Jonathan and this site.

Monkeypatching Beautiful Soup

25 March 2007, 1:59 PM CEST +0200

Since html2css is built upon Beautiful Soup, it is relatively easy to monkeypatch it. (Especially since there is a shortcut in the code, that lets Soup objects be used directly, achieving greater speed.)

Monkeypatching BS to use html2css is as easy as this:

>>> from beautifulsoup import BeautifulSoup
>>> from html2css import html2css
>>> setattr(BeautifulSoup, 'toCss', lambda soup: html2css(soup).display())
>>> soup = BeautifulSoup('<html id="foo"><body></body></html>')
>>> print soup.toCss()
html {}

body {}

html#foo {}

 html#foo body {}

There you go. (This also illustrates an advantage of Python’s explicit self declaration, in that toCss actually takes an argument (soup), which is then used as a self-declaration, meaning that toCss can be called without arguments — otherwise, it would have been soup.toCss(soup), which really isn’t optimal.)