0

I have found answers on stackoverflow that seem to be getting at my question, but I can't find something that I have been able to get to work. I have a really big list of strings like this:

db = ['a','b','c']

And I want to instantiate a class for each string, where unique strings would be the variable names:

a = MyClass()
b = MyClass()
c = MyClass()

I thought to convert the strings to variables, but this doesn't seem advisable from some answers I'm finding here on SO.

What is the best way of going about this?

4
  • use a dictionary ? Commented Nov 23, 2015 at 23:14
  • Just use a dict with the strings as keys and the class instances as values. That's pretty much how Python namespaces work anyway. Commented Nov 23, 2015 at 23:15
  • 1
    @letsc I have read that in a number of posts, but I'm not sure how to do this. Should the values all be an instantiation of a class with the same variable name? Like this: {'a':x, 'b':x, 'c':x} Commented Nov 23, 2015 at 23:17
  • 1
    You want something like instances = dict((k, MyClass()) for k in db). Or a dict comprehension, if you're on at least 2.7: instances = {k: MyClass() for k in db}. Commented Nov 23, 2015 at 23:25

1 Answer 1

1

I do not recommend this

You can add the names to the globals

names = ['a', 'b', 'c']
globals().update({name: MyClass() for name in names})
print(a)

or locals dictionary:

def myfunc():
    names = ['a', 'b', 'c']
    locals().update({name: MyClass() for name in names})
    print(a)

Using a dict

Better would be just to use a dict to store your MyClass-instances:

names = ['a', 'b', 'c']
data = {k: MyClass() for k in names}
print(data['a'])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.