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.

1 Answer 1

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:])
Sign up to request clarification or add additional context in comments.

1 Comment

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 stackoverflow.com/questions/452969/…

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.