dynamic variable referencing

bruno at modulix onurb at xiludom.gro
Wed Dec 7 04:44:28 EST 2005


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('@')])"



More information about the Python-list mailing list