Creating dynamically named variables from user input [duplicate]

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:

Leave a Comment