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'
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'
What you are trying to do is a bad practice.
What you really need is a dict
:
>>> dct = {'pasta': [1,2,3]}
>>> x = 'pas' + 'ta'
>>> dct[x]
[1, 2, 3]
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 use locals()
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 InteractiveInterpreter
could be used to access an object using a string, but that doesn't mean I'm going to.
Well, to do what you literally asked for, you could use locals
:
>>> locals()[x]
[1, 2, 3]
However it is almost always a bad idea to do this. As Sven Marnach pointed out in the comments: Keep data out of your variable names. Using variables as data could also be a security risk. For example, if the name of the variable comes from the user they might be able to read or modify variables that you never intended them to have access to. They just need to guess the variable name.
It would be much better to use a dictionary instead.
>>> your_dict = {}
>>> your_dict['pasta'] = [1, 2, 3]
>>> x = 'pas' + 'ta'
>>> your_dict[x]
[1, 2, 3]
Like other pointed out, you should normally avoid doing this and just use either a dictionary (in an example like you give) or in some cases a list (for example instead of using my_var1, my_var2, my_var3
-> my_vars
).
However if you still want to do that you have a couple of option.
Your could do:
locals()[x]
or
eval(x) #always make sure you do proper validation before using eval. A very powerfull feature of python imo but very risky if used without care.
If the pasta is an object attribute you can get it safely by:
getattr(your_obj, x)