Python- Use value of pop as object name

556 views Asked by At

I am taking in user input and creating objects with it. So I have a list of acceptable object names (A-E). What I figured I could do was pop(0) and use the return value as the name of the object. This way there is never a duplicate object name upon entry. Here is what I have so far I just cannot figure out how to assign the popped value to the name of the object properly.(Net is a defined class at the start of the program)

userIP = None

name_list = ['A', 'B', 'C', 'D', 'E']

while True:
    if userIP == 'end':
        break
    userIP = input("Enter IP (type 'end' to exit): ")
    userMask = input("Enter Mask: ")
    name_list.pop(0) = Net(userIP, userMask)
    print("The object just created would print here")
2

There are 2 answers

2
kindall On BEST ANSWER

Put the results in a dictionary. Don't try to create variables with specified names. That way lies madness.

net_dict = {}

# ...

name = name_list.pop(0)
net_dict[name] = Net(userIP, userMask)
print(net_dict[name])

If you have them in a container, you may find you don't actually need the names. What are the names for, in other words? If the answer is just "to keep them in some order," use a list:

net_list = []

# ...

net_list.append(Net(userIP, userMask))
print(net_list[-1])
1
TessellatingHeckler On

I just cannot figure out how to assign the popped value to the name of the object properly

It's not easy to do that, because it's not very useful to do that. What if you do get it to work, and you want to use the thing later on?

name_list.pop(0) = Net(userIP, userMask)
print ?.userMask

What do you put for the ? when you have no idea which variable name was used?

The right approach to this is @kindall's answer, or similar. But it is possible ( How can you dynamically create variables via a while loop? ) but not recommended.