[lxml-dev] Instantiated ObjectifiedElement

Stefan Behnel stefan_ml at behnel.de
Thu Feb 21 07:10:29 CET 2008


Hi,

Evan Grim wrote:
> I've run into some curious behavior when trying to do something a bit
> non-standard with objectify.  The code snippet below causes a hard crash.  I
> know this isn't part of what is anticipated as normal use, but since it causes a
> crash I figure it's worth bringing up here to at least get some comments.
> 
> <code>
> from lxml import etree, objectify
> 
> class parent(objectify.ObjectifiedElement):
>     pass
> 
> p = parent()
> print p.tag
> </code>

A crash is the expected result here. The docs say:

"""Note that you cannot (or rather must not) instantiate this class yourself.
lxml.etree will do that for you through its normal ElementTree API.
"""

http://codespeak.net/lxml/element_classes.html


> My use case here is that I'm trying to make a package that acts like objectify,
> but enforces schema restrictions.

Not sure what exactly you mean. Do you mean data types, structural validity,
or both? How would you enforce restrictions during multi-step changes to the
tree, where the first couple of steps do not result in a valid tree by themselves?

Doesn't validation do what you want?


> I'm trying my hand at writing custom classes
> that will do this, but maintain the nice interface that objectify provides.

That should be doable without instantiating any classes directly. Just
override __setattr__ and __setitem__ and intercept the cases where attributes
are assigned. Use your subclasses as described here:

http://codespeak.net/lxml/objectify.html#advanced-element-class-lookup
http://codespeak.net/lxml/element_classes.html#setting-up-a-class-lookup-scheme

Stefan



More information about the lxml-dev mailing list