1

I checked I have a string whose content is a function name, how to refer to the corresponding function in Python? but it is not the question I want to ask.

The question is: I have a string 'ABC' and I want to create an instance of class ABC as:

my_obj = ABC ()

The input 'ABC' is read from Python arguments (argparse).

The class is already defined and imported.

jpp
  • 159,742
  • 34
  • 281
  • 339
mommomonthewind
  • 4,390
  • 11
  • 46
  • 74

1 Answers1

0

You can use a dictionary:

d = {'ABC': ABC}  # where ABC is the class object

my_obj = d['ABC']()

This should be preferable to solutions using global (poor practice) and eval (security risks).

This may seem cumbersome until you realise that classes and class instances are first class objects in Python. You should never rely on evaluating strings to call a Python object. Be explicit, even if it's not elegant.

jpp
  • 159,742
  • 34
  • 281
  • 339