Natsume
Natsume

Reputation: 901

Convert String to Object name

I needed help on this one. How do I convert a string into a variable/object/instance name, since I don't know how to categorize this.
Assuming my code is:

a = {}
b = {}

class Test:
    def getKeys(self, var):
        return var.keys() #where var refers to the dictionary and its a string initially

Upvotes: 9

Views: 28701

Answers (3)

Dr-Bracket
Dr-Bracket

Reputation: 5494

You're looking for the setattr builtin method. You'll also need an object to perform this on.

obj = lambda: None # Create an empty object without needing to make a class (functions are objects)
setattr(obj, "hello", "world")
obj.hello # returns "world"

Upvotes: 0

Isaac
Isaac

Reputation: 91

It's been forever since I've done anything with Python but I do remember having this problem once. I suggest you look into the eval() function.

Upvotes: 9

Blckknght
Blckknght

Reputation: 104712

If I understand correctly, your variable var is a string that might be "a" or "b". You want to use that letter to pick the correct dictionary global variable to look in.

I suggest putting your dictionaries into another dictionary, with keys you can use to look it up by name:

my_dicts = {"a":a, "b":b}

class Test:
    def getkeys(self, dict_name):
        return my_dicts[dict_name].keys()

However, this may be simply an issue of design. Instead of sending a variable name to the getkeys method, why not simply send the dictionary itself and use your current code?

Instead of Test().getkeys("a"), call Test().getkeys(a) (no quotation marks).

Upvotes: 4

Related Questions