Creating dynamically named variables from user input [duplicate]

I'm just learning to program and am learning Python as my first language. As an exercise I'm trying to write an address book program. New contact are created by the user using the command prompt. New contacts are object instances of the Contacts class.

I know how to instantiate a class object from within the code, but how do I create one with a variable name based on user input? Say I prompt the user for a name -- how do I take that info and use it for the variable name of my new object?

Thanks!!


From the comments, it turns out you are asking about something that gets asked more than once on here. "How can I create dynamically named variables".

Answer: Don't do this. Chances are there are better ways to solve the problem.

Explanation:

If you were to create dynamically named variables, you don't quite have a good handle to them once they are created. Sure there are ways to check the globals and local scopes to see what is there. But the fact is that you should have definitive control over what is being created.

What you should do is put them into a dictionary:

people = {}
name = raw_input("What name? ") # "person"
people[name] = User(name)

print people
# {'person': <User: "person">}

print people.keys()
# ['person']

This way you are not creating arbitrary variables in your namespace. You now have a dictionary of keys and objects as values. It is also a can of worms to allow a user-supplied input to drive the naming of a variable.

For more info, just search on here for the same topic and see numerous examples of why you should not do this. No matter what examples you see showing you how to use globals(), etc, please take my advise and don't go that route. Love and enjoy..and maybe hug and kiss, your dictionary.

References:

  • How can you dynamically create variables via a while loop?
  • Is it possible to "dynamically" create local variables in Python? (DONT DO THIS)