Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a string with the same name of an object in Python to access the object itself?

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'
like image 248
Luis Damiani Avatar asked Feb 22 '12 14:02

Luis Damiani


People also ask

Can objects have the same name Python?

Thanks. Objects dont "have names", names can refer to objects, but they are free to be re-assigned to different names at any time.

Can you write code to determine the name of an object in Python?

format(self.name) obj1 = Test('Willy') print(obj1) obj2 = Test('Betty') print(obj2) See what I did? I gave the objects different names to their variable names. If this is all you want to do, making an object return a stored value if you print it, yeah, you can use __str__ or __repr__.

Can two variables have the same name Python?

Variable names in Python are case sensitive. Two variables with the same name but different casing are considered as two different variables. For example, websitename is considered a different variable to websiteName because of the capitalization of the letter “N“.

How do you use a string name as a variable in Python?

String Into Variable Name in Python Using the vars() Function. Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.


1 Answers

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.

like image 170
Rik Poggi Avatar answered Oct 06 '22 10:10

Rik Poggi