ANN: XML builder for Python

Jonas Galvez jonas at codeazur.com.br
Thu Jul 3 16:49:15 EDT 2008


Stefan Behnel wrote:
> Interesting. Is the "+" actually required? Are there other operators
> that make sense here? I do not see what "~" or "-" could mean.
> Or is it just a technical constraint?
> I'm asking because I consider adding such a syntax to lxml as
> a separate module. And I'd prefer copying an existing syntax over
> a (badly) home grown one.

I believe it's related to something tricky about the with statement.

You have to be able to call the "element builder" both in the with statement:

with xml.element ...

And also inside the block itself:

with xml.element ...:
   xml.otherelement()

Except the with element expects an object that implements __enter__()
and __exit__().

The solution I found to this was to make __getattr__() return a
ready-to-use object that implements those methods while also taking
keyword parameters but *not* text. So for instance:

with xml.element(foo=1):
  xml.foo("bar")

Will work (<element foo=1><foo>bar</foo></element>) but:

with xml.element("text", foo=1):
   xml.foo("bar")

Will not. Also, in inline calls to the builder you have to explictly
set the element-content (value) parameter, even if it's simply None,
so __call__() can identify that you're (supposedly) calling it inline
and not with the 'with' statement.

That is an acceptable tradeoff, however, considering you would rarely
append text nodes right after an element while also having other child
elements. I believe my xmlbuilder will work well for Atom, XML-RPC,
SOAP etc, but definitely not for HTML! :)

Overriding + is a rather clever way to prevent this (so you can
actually know you're calling it inline), but I don't really see a need
for it for most things XML.

--Jonas Galvez, http://jonasgalvez.com.br/log



More information about the Python-list mailing list