Hello world!
>>> print html.a(href='#top')('return to top') return to top """ from cgi import escape try: import xml.etree.ElementTree as ET except ImportError: # Python < 2.5 import elementtree.ElementTree as ET __all__ = ['html'] default_encoding = 'utf-8' class _HTML: def __getattr__(self, attr): if attr.startswith('_'): raise AttributeError attr = attr.lower() if attr.endswith('_'): attr = attr[:-1] if attr.find('__') != -1: attr = attr.replace('__', ':') if attr == 'comment': return Element(ET.Comment, {}) else: return Element(attr, {}) def __call__(self, *args): return ElementList(args) def quote(self, arg): if arg is None: return '' return escape(unicode(arg).encode(default_encoding), 1) def str(self, arg, encoding=None): if isinstance(arg, str): return arg elif arg is None: return '' elif isinstance(arg, unicode): return arg.encode(default_encoding) elif isinstance(arg, (list, tuple)): return ''.join(map(self.str, arg)) elif isinstance(arg, Element): return str(arg) else: return unicode(arg).encode(default_encoding) html = _HTML() class Element(ET._ElementInterface): def __call__(self, *args, **kw): el = self.__class__(self.tag, self.attrib) if 'c' in kw: if args: raise ValueError( "You may either provide positional arguments or a " "'c' keyword argument, but not both") args = kw.pop('c') if not isinstance(args, (list, tuple)): args = (args,) for name, value in kw.items(): if value is None: del kw[name] continue kw[name] = unicode(value) if name.endswith('_'): kw[name[:-1]] = value del kw[name] if name.find('__') != -1: new_name = name.replace('__', ':') kw[new_name] = value del kw[name] el.attrib.update(kw) el.text = self.text last = None for item in self.getchildren(): last = item el.append(item) for arg in flatten(args): if arg is None: continue if not ET.iselement(arg): if last is None: if el.text is None: el.text = unicode(arg) else: el.text += unicode(arg) else: if last.tail is None: last.tail = unicode(arg) else: last.tail += unicode(arg) else: last = arg el.append(last) return el def __str__(self): return ET.tostring(self, default_encoding) def __unicode__(self): # This is lame! return str(self).decode(default_encoding) def __repr__(self): content = str(self) if len(content) > 25: content = repr(content[:25]) + '...' else: content = repr(content) return '