Created
October 2, 2012 17:31
-
-
Save ods/3821453 to your computer and use it in GitHub Desktop.
eplant prototype implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
from lxml.builder import ElementMaker | |
from lxml import etree | |
class QName(unicode): | |
def __new__(cls, maker, name): | |
self = unicode.__new__(cls, maker._namespace+name) | |
self._maker = maker | |
self._name = name | |
return self | |
def __call__(self, *args, **kwargs): | |
return self._maker(self._name, *args, **kwargs) | |
class Namespace(ElementMaker): | |
def __getattr__(self, name): | |
return QName(self, name) | |
class ElementPlant(object): | |
def __init__(self, default_namespace=None, nsmap=None, **options): | |
self.nsmap = dict(nsmap or {}) | |
if default_namespace: | |
self.nsmap[None] = default_namespace | |
self.options = options | |
def namespace(self, name): | |
namespace = self.nsmap[name or None] | |
return Namespace(namespace=namespace, nsmap=self.nsmap, **self.options) | |
def namespaces(self, *names): | |
return tuple(self.namespace(name) for name in names) | |
plant = ElementPlant( | |
default_namespace = 'http://default/', | |
nsmap = { | |
'foo': 'http://foo/', | |
'bar': 'http://bar/', | |
} | |
) | |
default, foo, bar = plant.namespaces('', 'foo', 'bar') | |
doc = default.root( | |
foo.title({bar.x: 'a'}, 'title text'), | |
bar('small-body', 'body text'), | |
) | |
print(etree.tostring(doc, pretty_print=True)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment