I'm looking for a way to access variables from strings.
Like this:
A1 = {}
B1 = {}
C1 = {}
mylist = ["A","B","C"]
for blurb in mylist:
blurb1.foo()
Right now I'm using if/elif constructions in such cases:
if blurb == "A":
A1.foo()
elif blurb == "B":
B1.foo()
elif blurb == "C":
C1.foo()
That works, but surely there's a more elegant way of doing it?
I would like to create and access objects from strings.
So if I have a function that returns a string, I want to create e.g. a list using this string as the list name, and then do stuff with that list.
x = foo() # foo returns a string, e.g. "A"
# create list named whatever the value of x is
# in this case:
A = []
Isn't there anything more elegant than preparing lists for all possible outcomes of x and using long elif constructions or dictionaries? Do I have to use eval() in that case? (I'm hesitant to use eval(), as it's considered dangerous.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With