Reputation: 13
I can't find the answer anywhere.
I have a class called "vrf".
I have an input file.
As Python iterates through the lines of this input file, every time it sees the word vrf, I want to create an object named after the next word.
So if it reading the line "ip vrf TESTER", I would like to dynamically create an object named TESTER of type vrf.
TESTER = vrf()
How in the world do I do this?
I've tried:
line.split()[2] = vrf()
Doesn't work.
Upvotes: 1
Views: 843
Reputation: 3525
What you're trying to do is not a great idea, instead use a dictionary, or if your object has an instance variable that stores name information such as name
, bind the data there.
objs = {}
objs[line.split()[2]] = vrf()
or (if available)
v = vrf(line.split()[2])
v = vrf(); v.name = line.split()[2]
Sample output:
print objs
>>> {'vrf' : <__main__.vrf instance at 0x7f41b4140a28>}
Upvotes: 0
Reputation: 385940
Generally speaking, dynamically created variable names are a bad idea. Instead, you should create a dictionary where the name is the key and the instance is the value
In your case it would look something like this:
objects = {}
...
object_name = line.split()[2]
objects[object_name] = vrf()
Then you can access it this way for your example: objects["TESTER"] will give you the corresponding vrf instance.
Upvotes: 2
Reputation: 6360
The globals()
dictionary can be edited to do this:
>>> globals()['TEST'] = vrf()
>>> type(TEST)
# <class 'vrf'>
Upvotes: 0
Reputation: 15071
Why don't you just use a dictionary?
object = {}
object[line.split()[2]] = vrf()
Upvotes: 1