For example, in the code below I would like to obtain the list [1,2,3] using x as a reference.
In[1]: pasta=[1,2,3]
In:[2]: pasta
Out[2]: [1, 2, 3]
In [3]: x='pas'+'ta'
In [4]: x
Out[4]: 'pasta'
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What you are trying to do is a bad practice.
What you really need is a
dict:This is the right data structure for the actual task you’re trying to achieve: using a string to access an object.
Other answers suggested (or just showed with a worning) different ways to do that. Since Python is a very flexible language, you can almost always found such different ways to follow for a given task, but “there should be one– and preferably only one –obvious way to do it”[1].
All of them will do the work, but not without downsides:
locals()is less readable, needlessly complex and also open to risks in some cases (see Mark Byers answer). If you uselocals()you are going to mix the real variables with the database ones, it’s messy.eval()is plain ugly, is a “quick-and-dirty way to get some source code dynamically”[2] and a bad practice.When in doubt about the right way to choose, tring to follow the Zen of Python might be a start.
And hey, even the
InteractiveInterpretercould be used to access an object using a string, but that doesn’t mean I’m going to.