Simply Jonathan

Monkeypatching Beautiful Soup

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.)

This is Simply Jonathan, a blog written by Jonathan Holst. It's mostly about technical topics (and mainly the Web at that), but an occasional post on clothing, sports, and general personal life topics can be found.

Jonathan Holst is a programmer, language enthusiast, sports fan, and appreciator of good design, living in Copenhagen, Denmark, Europe. He is also someone pretentious enough to call himself the 'author' of a blog. And talk about himself in the third person.