1

Is there a way to use a string (in my case read from a file) to find a class with the name matching the string, then create an instance of that class. For example:

class FirstClass:
    def __init__(self, arg1):
        self.arg = arg1

values = ','.split('FirstClass', 'argument')
# need the magic for this:
values[0](*values[1:])

But of course using values[0] doesn't work there, because it's a string, not a class. Is there a way to automatically convert the string to the class there? Especially if I have many classes and cannot know in advance which one to instantiate, like reading the values from a CSV and wanting the right class to handle a line.

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67

1 Answers1

4

You can access a variable by name using locals() or globals() respectively. In your case this would work as such:

locals()[values[0]](*values[1:])
Parker Hoyes
  • 2,118
  • 1
  • 23
  • 38
  • 3
    You probably want `globals()` though so that it works within a function scope. Also see this answer for if the class is part of another module you want to dynamically load http://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname – Peter Gibson May 27 '15 at 02:18