Generate variables at run time?
lazypointer at yahoo.com
Thu Jan 9 05:45:45 CET 2003
Thanks to all for the good suggestions.
I have been using REXX for years for all my scripting needs. In REXX, I can
use any string as a variable with no special handling.
Here is the project:
A server supplies an alphanumeric data stream over an internet socket. The
data is output from a train control system. Trains constantly enter and
leave the controlled territory, and each has a unique ID. I want to use a
class named "train", and name each new instance based on this ID. For
example, train 123 will cause creation of T123=train(). While the train is
in the system, it will be frequently updated based on new data, then it will
be destroyed when the train leaves the system.
for the curious:
In REXX, for a similar situation, I use a stem "train", then add the train
number, then add each attribute as events are reported.
train. = 0
train.123 = 1 (value represents the number of cars in train)
train.123.stat = 1 (0 if stopped, 1 if moving)
train.123.doors = 1 (1 if closed, 0 if open)
Judging by the excellent advice I got from one question, I think I'm gonna
like this Python, Monty!
"Marko" <junkthis at blueyonder.co.uk> wrote in message
news:avi7k2$g5tob$1 at ID-89047.news.dfncis.de...
> Byron Morgan wrote:
> > Is there any way in Python to generate a new variable name based on
> > data? I have tried the eval() function, but this gets rejected, if
> > the variable doesn't already exist.
> > There has to be a way to do this, but I can't find it, probaly
> > because I am just starting to learn Python.
> > Byron
> As others have already pointed out you could use dicts or classes for
> However, you might not be aware that setattr and delattr also work at
> level, so you could also do this:
> new_var_name = "abc"
> setattr(sys.modules[__name__], new_var_name, "123")
> ...which obviously creates a variable called abc with the value 123. You
> then delete it with:
> delattr(sys.modules[__name__], new_var_name)
> I personally don't think this is the most elegant solution and I would
> suggest using dictionaries instead, but it does work this way too.
More information about the Python-list