473,406 Members | 2,439 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

dynamic variable referencing

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. . .

The purpose is to create an XML tree myself by means of OBJECT.
("string").__setattr(name,value). I eventually want to be able to
say BOOK[0].AUTHOR.FIRSTNAME . . . that kind of thing. I've seen
existing libraries, but I'd really rather know how to do it myself.
Any assistance would be appreciated.
Regards,
Michael
Dec 7 '05 #1
2 1373
Michael Williams wrote:
- 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. . .

<snip>


It's not exactly clear what you're trying to tell us here. Basically, what I
guess you want is:

getattr(object,"varname")

This retrieves the value that is bound to varname at "namespace" object. You
cannot retrieve a variable per se in Python, as a variable is just a name
that is a binding to an object.

The second part of what you're trying to do sounds more like stacking
objects. I'll just give it a shot and implement a little bit to test on.
You'll have to extend it to suit your needs... ;-)

class xmlnode(object):

def __init__(self):
self.__subnodes = {}
self.__value = ""

def __getattr__(self,item):
if item == "value":
return self.__value
elif item.startswith("_"):
raise AttributeError, item
elif item not in self.__subnodes:
self.__subnodes[item] = xmlnode()
return self.__subnodes[item]

def __setattr__(self,item,value):
if item.startswith("_"):
super(xmlnode,self).__setattr__(item,value)
elif item == "value":
assert isinstance(value,(str,unicode))
self.__value = value
else:
assert isinstance(value,(str,unicode))
if item not in self.__subnodes:
self.__subnodes[item] = xmlnode()
self.__subnodes[item].value = value

def __delattr__(self,item):
if item.startswith("_"):
super(xmlnode,self).__delattr__(item)
elif item == "value":
self.__value = None
else:
try:
del self.__subnodes[item]
except KeyError:
raise AttributeError, item

def toXML(self,name):
rv = ["<%s>" % name]
for sname, sitem in self.__subnodes.iteritems():
rv.append(sitem.toXML(sname))
if self.__value is not None:
rv.append(self.__value)
rv.append("</%s>" % name)
return "".join(rv)

This implements a simple XML-tree builder with a very specific output format
(tags contain only one string value, which always comes after any subtag
that they might contain, and subtag order is random). The "tricky" part is
in the __*attr__ logic to get subnodes.

Example of usage:
a = test.xmlnode()
a <test.xmlnode object at 0x2aaaaab57890> a.value = "test"
a.toXML("root") '<root>test</root>' a.book = "welcome"
a.anotherbook = "bye"
a.toXML("root") '<root><anotherbook>bye</anotherbook><book>welcome</book>test</root>' a.book.value 'welcome' a.book.anotherbook.somethingelse.thisislong = "test"
a.toXML("root") '<root><anotherbook>bye</anotherbook><book><anotherbook><somethingelse><thi sislong>test</thisislong></somethingelse></anotherbook>welcome</book>test</root>'


HTH!

--- Heiko.
Dec 7 '05 #2
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 'o****@xiludom.gro'.split('@')])"
Dec 7 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Simon | last post by:
Am using the following code. <script language="JavaScript1.2"> function setquantity(productindex,productquantity) { //create the reference object irefname_none = eval("document." +...
1
by: pbb | last post by:
Is it possible to declare a variable by referencing another variable as the type? Something like this: 'Declare variable to hold variable type Dim strVariableType as String 'Set variable =...
1
by: yuriy_zubarev | last post by:
Greetings, Simple scenario: I have objects that need to be persisted in XML. The declaration is as follows: public class Zoo { protected Animal animals;
8
by: Eyeawanda Pondicherry | last post by:
I have put some code together that creates an enum dynamically from some database values. The enum can be read perfectly by an application that references the dynamically generated dll. If I...
28
by: Dennis | last post by:
I have a function which is called from a loop many times. In that function, I use three variables as counters and for other purposes. I can either use DIM for declaring the variables or Static. ...
26
by: Jerim79 | last post by:
I need to create a form that takes a number that the user enters, and duplicates a question the number of times the user entered. For instance, if the customer enters 5 on the first page, when...
11
by: downwitch | last post by:
Hi, I'm using a 3rd-party app's back end which stores SQL statements in a table, so I have no choice but to use dynamic SQL to call them (unless someone else knows a workaround...) Problem...
9
by: Christopher Koeber | last post by:
Hello, I am attempting to perform a PHP installation on an Apache 2.2.6 web server instance that is loaded on a Windows 2003 server operating system (R2 SP2). I have a third party application...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.