0

I've looked everywhere for this but haven't found a suitable answer yet and I don't want to use a dictionary.

How can I convert a string to a variable name? For example I have this call:

object.variable

This variable is defined in the object. However I have a LOT of variables (for a reason) and more to come. It seems stupid to do this:

s = 'variable'
if s == 'variable': object.variable
elif s == 'variable2: object.variable2
etc....

So is there a way to convert a string to a variable name?

5
  • 1
    Have you considered using a dict? Commented Apr 22, 2013 at 6:34
  • I implicitly stated I don't want to use a dictionary, so yes I have considered it but don't think it's the best solution. Commented Apr 22, 2013 at 6:37
  • @Tim: Just an aside; if you find running into this problem, you are probably doing something wrong in the design of the code. While it is possible, it is extremely unlikely that your use case is a unique one in which gettattr() access to attributes is a good solution. Commented Apr 22, 2013 at 6:58
  • @JoelCornett, to be honest, I'm a good programmer but certainly not the best so the possibility of doing something wrong in the design is most definitely an option. However, I've no idea how to do it differently. Commented Apr 22, 2013 at 7:11
  • Could you use object[s]? (Or do you already use __getitem__ for something else?) Commented Apr 22, 2013 at 7:49

1 Answer 1

1
getattr(object, variable)

However I don't see any good reason to be accessing attributes like this...

Sign up to request clarification or add additional context in comments.

1 Comment

Well, it's just a program I use for my thesis so know one will ever use it again. Each attribute has different information stored about the object and I want to use them all to compare in machine learning.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.