Python: access variable from string [duplicate]

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 with a switch statement (from c/java/etc.) Note that the lookup.get (instead of just lookup[blurb] handles the case where blurb is something other than one of the values you defined it for… you could also wrap that in a try/except block.


Updated answer based on your revised question, which builds on what Joachim Pileborg had said in another answer.

There are probably better/cleaner ways to do this, but if you really want to set/get via strings to manipulate global objects, you can do that. One way would be:
To create a new object named “myvariable” (or to set “myvariable” to a new value)

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

To get the object “myvariable” is assigned to:

globals().get(joe,None) 

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

So for later example, you could do something like:

for myobject in mylist:
    # add myobject to list called locus
    # e.g. 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

Leave a Comment