Python: accessing a variable from a string

This is probably something very simple and simple, and I probably just looked for errors for the wrong terms, but hopefully someone here can help me. (I'm still new to programming, which is probably obvious from this question.)

I am looking for a way to access variables from strings.

Like this:

A1 = {} B1 = {} C1 = {} mylist = ["A","B","C"] for blurb in mylist: blurb1.foo() 

Now I use if / elif constructs in such cases:

 if blurb == "A": A1.foo() elif blurb == "B": B1.foo() elif blurb == "C": C1.foo() 

It works, but of course there is a more elegant way to do it?

Thanks for any help! Lastalda


Edit2: trying to clarify again (sorry for not being very consistent before, it's hard for me to get this through):

I would like to create and access objects from strings.

So, if I have a function that returns a string, I want to create, for example. list using this string as the name of the list, and then make stuff with this list.

 x = foo() # foo returns a string, eg "A" # create list named whatever the value of x is # in this case: A = [] 

Is there nothing more elegant than preparing lists for all possible outcomes of x and using long elif constructs or dictionaries? Should I use eval () in this case? (I hesitate to use eval () as it is considered dangerous.)

Hopefully this is finally clear. Any help is still appreciated!

+1
source share
4 answers

I think you want something like

 lookup = {"A": A1, "B": B1, "C": C1} obj = lookup.get(blurb,None) if obj: obj.foo() 

This is usually suggested when someone wants to do something using the switch statement (from c / java / etc.). Please note that lookup.get (and not just lookup [blurb] handles the case where the ad is something other than one of the values ​​you defined for ... you could also wrap this in a try / except block.


Updated answer based on your revised question, which is based on what Joachim Pieleborg said in another answer.

There are probably better / cleaner ways to do this, but if you really want to set / get through strings to manage global objects, you can do it. One way: To create a new object named "myvariable" (or set "myvariable" to a new value)

 joe = "myvariable" globals().update([[joe,"myvalue"]]) 

To get the object "myvariable" is assigned:

 globals().get(joe,None) 

(or, as mentioned in another answer, you can use try / except with a direct hash instead of using get)

So, for the following example, you can do something like:

 for myobject in mylist: # add myobject to list called locus # eg if locus == "A", add to list "A", if locus == "B" add to list B etc. obj = globals().get(myobject.locus,None) # get this list object if not obj: # if it doesn't exist, create an empty list named myobject.locus obj = [] globals().update([[myobject.locus,obj]] obj.append(myobject) #append my object to list called locus 
+9
source

You can get the module object and use getattr to get variables / functions from the string:

 import sys A = {} B = {} C = {} modname = globals()['__name__'] modobj = sys.modules[modname] mylist = ["A","B","C"] for name in mylist: print '%s : %r' % (name, getattr(modobj, name)) 

The above program will print:

  A: {}
 B: {}
 C: {}

However, this has nothing to do with the “wildcards” that you refer to in your question, but you do not show the search for “wildcards”.

+5
source

use eval() .

Example:

 A1 = [] B1 = [] C1 = [] mylist = ["A","B","C"] for blurb in mylist: eval("%s1.append(blurb)" % blurb) print A1,B1,C1 >>> ['A'] ['B'] ['C'] 

and for your code it could be:

 for blurb in mylist: eval("%s1.foo()" % blurb) 
+2
source

It looks like you just need a dictionary and look for it, and not run a bunch of checks.

 dict_look_up = {'A' : A1, 'B' : B1, 'C' : C1} try: dict_look_up[blurb].foo() except KeyError: #whatever on item not found 

try/except blocks are incredibly important in Python (it's better to ask forgiveness than permission), so if you are learning, I recommend using them from the very beginning.

+1
source

All Articles