dynamic variable referencing

Michael Williams mwilliams at mgreg.com
Wed Dec 7 09:01:43 EST 2005


Bruno,

Thanks, but the whole reason I need it is to create objects in the  
tree on the fly.  Every implementation I've seen of Element tree  
manually assigns values to the nodes and manually places them.  All I  
care about is that any tags they have are in my list of  
"valid_tags".  Otherwise they can be in any order, etc.  For instance  
they could have:

<book>
	<title>the good one</title>
	<author>ted</author>
	<year>1945</year>
</book>

or

<book>
	<year>1945</year>
	<title>the good one</title>
	<author>ted</author>
</book>


I want to avoid the line by line assignments like this:


if name == "book":
	# do book stuff
if name == "title":
	#do title stuff


I want to assign objects on the fly:


if name in valid_tags:
	object = Element(name)
	if condition:
		object = SubElement(Super, object)


I'd still need an algorithm that walked the tree and created it for  
me.  That way, if in fact I decide to allow more XML tags in the  
future, it's simply a matter of adding a few "valid_tags" to the list  
and it automatically allows them to be created.  Does that make any  
sense?

Thanks again,
Michael


On Dec 7, 2005, at 5:20 AM, python-list-request at python.org wrote:

> Michael Williams wrote:
>> I would RTM, but I'm not sure exactly what to look for.  Basically, I
>> need to be able to call a variable dynamically.  Meaning  
>> something  like
>> the following:
>>
>>             -  I don't want to say     OBJECT.VAR      but rather
>> OBJECT. ("string")      and have it retrieve the variable (not the  
>> value
>> of  it) if in fact it exists. . .
>
> getattr(obj, 'name', defaultvalue)
>
> You can also implement the special methods __getitem__ and __setitem__
> to allow indexed access to attributes, ie:
>
> class FalseDict(object):
>   def __init__(self, toto, tata):
>      self.toto = toto
>      self.tata = tata
>   def __getitem__(self, name):
>      return getattr(self, name)
>   def __setitem__(self, name, value):
>      setattr(self, name, value)
>
> f = FalseDict('toto', 'tata')
> f['toto']
> f['tata'] = 42
>
>>
>> The purpose is to create an XML tree myself
>
> Don't reinvent the wheel. ElementTree (and it's C based brother) are
> very good at this.
>
> -- 
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split 
> ('.')]) for
> p in 'onurb at xiludom.gro'.split('@')])"
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20051207/3324d937/attachment.html>


More information about the Python-list mailing list