""" An experiment using breve xml library, and metaclass.
Author: Ben West
Email: bewest at gmail
blog: http://bewest.wordpress.com/
I hang out on freenode.
Breve is available at <URL:http://breve.twisty-industries.com/>.
From the website:
-----------------
Breve is a Python template engine that is designed to be clean and elegant
with minimal syntax.
Like Stan (and unlike most Python template engines), Breve is neither an XML
parser nor PSP-style regex engine. Rather, Breve templates are actual Python
expressions. In popular parlance, Breve is an internal DSL.
This seemed like a really elegant idea to me. I began to wonder about
generating classes that would allow easy manipulation of XML documents, given
a schema. The simplest way to create a new xml tag is to call Proto(),
with the name of the tag as the argument. I don't know if there is a way to
also control the attributes as you are generating the XML. If there's not,
there should be.
Once, I got some simple hello world tests going with breve, I started fooling
around with ways to create new sets of tags. I kept fooling around, trying to
reduce the number of steps necessary, until I came up with the current
contents of this experiment.
The basic idea is to reduce the amount of work required for an author to start
creating valid templates in breve for an known XML vocabulary that has a
schema. This experiment goes far enough to show that this feature is
definitely possible.
The customtags class implements a callable. The reason it is a class is so
that other authors might override certain aspects of it, such as findTags,
getDocString. When an instance is called, it will construct a type (actually
a metaclass) in which the __dict__ contains all the breve tag's found by
findTags. As a bonus, the docstring is also populated, providing the author
with rich documentation on that class, potentially coming directly from the
schema.
Using this technique, it would be possible to design a package, in which the
__init__.py inspects a directory for the presence of schema files. At
runtime, this package could create all the classes necessary to start creating
templates for those schemas. Any time the schema changes, the class also
changes, on the next import. I believe this makes it more desirable over
code generators that create python code containing the tags on disk.
"""
import sys
import breve
from breve import tags
from breve.tags.html import tags as T
import doctest
def hello_world():
"""Hello world example.
>>> str( hello_world() )
'<div>hello world</div>'
"""
# breve takes care of html automatically.
return T.div[ 'hello world' ]
def simple_customtag():
"""Simple custom tag hello world example.
>>> str( simple_customtag() )
'<foo>hello world</foo>'
"""
newtag = tags.Proto('foo')
return newtag['hello world']
# first define the callable class I discussed above. It's instances will be
# responsible for return a type representing an XML schema when called.
class customtags(object):
"""This is an experiment to dynamically provision some tags.
Anyway, this is neat because you can load this up in the python shell and
get detailed help. This is useful for having a config file that specifies
the location of some XML schema. You can change the schema, and your code
will update automatically.
XXX: This is probably bad practice because if something goes weird, it would
be nearly impossible to debug ;-)
However, this would faciliate importing schema definitions as a module, and
getting rich help from the schema's documentation using the normal python
methods. (Eg, imaging putting this in __init__.py, and creating a class for
each schema in that directory.)
For example:
>>> class MyTags(customtags()()): pass
>>> newtags = MyTags() # instantiate it
>>> str( newtags.feed['hello world'] )
'<feed>hello world</feed>'
This example consisted of just plain calls with no parameters, so it may
seem a bit over the top, without a full implementation of all the features
previously described.
"""
def __call__(self, *args, **kwds):
"""Construct and then return a type representing a schema.
"""
doc = self.getDocString()
class metaTagSet(type):
def __new__(cls, classname, bases, classdict):
classdict['__doc__'] = doc
# add each element as a breve tag to the new class's __dict__
for e in self.tags.keys():
classdict[e] = tags.Proto(e)
# TODO: is this preferred, or should I use super()?
return type.__new__(cls, classname, bases, classdict)
# create a quick wrapper, so we can use normal inheritance syntax.
class TagSet(object):
__metaclass__ = metaTagSet
return TagSet
def __init__(self):
self.tags = self.findTags()
def getDocString(self):
"""Returns the doc string for the class.
"""
doc = """A bunch of tags for use in breve, an s-expression xml generator.
\n"""
for e in self.tags.keys():
doc += "%s: %s\n" % (e, self.tags[e])
return doc
def findTags(self):
"""In the future, this could simply parse a schema.
"""
return {
'feed' : """A feed elements contains comments, service, and
collection. It is the root element.""",
'comments' : """comments is for containing a comment from one source.""",
'service' : """A service descripts a set of capabilities.""",
'collection' : """Useful for containing members, and related things."""}
# for now, just a dumb dictionary of element names and a doc string.
# wow... dynamically bind properties to a /class/ at runtime!
# imagine an __init__.py that inspected the contents of a directory for schema
# files, and then exported one of these for each schema. :-).
# You get a nice literate programming environment, because your declaritive
# documentation gets completely re-used in your procedural code, without you
# repeating yourself at all.
class CustomTags(customtags()()):
pass
def main(args):
"""A slightly more involved test...
erm. basically if we get back xml the test works. (and it does)
"""
template = hello_world()
#t = breve.Template ( tags.html.tags, doctype = '', xmlns = '' )
print template
newtags = CustomTags()
print newtags.feed[
[newtags.comments[ newtags.service, newtags.service ] for i in \
xrange(3)],
newtags.collection,
newtags.collection,
"hello world"
]
if __name__ == '__main__':
main(sys.argv)
doctest.testmod()