Search code examples
pythonvariablesobjectobjectname

Python- Use value of pop as object name


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")

Solution

  • 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])