1

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.

3
  • 1
    why don't you just use a dictionary? Commented Aug 4, 2016 at 14:59
  • A hack is to do globals()[line.split()[2]] = vrf(), but the dict solution is better, as it is not sane to modify globals (or locals) directly. Commented Aug 4, 2016 at 15:05
  • Suggested reading: Why you don't want to dynamically create variables and Keep data out of your variable names. To which I would add "Keep language tags out of your question's title." Commented Aug 4, 2016 at 15:12

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Why don't you just use a dictionary?

object = {}
object[line.split()[2]] = vrf()

Comments

0

The globals() dictionary can be edited to do this:

>>> globals()['TEST'] = vrf()
>>> type(TEST)
# <class 'vrf'>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.