1

I have a python class called CreateDB, with a method execute(module_name). The module_name variable is a string and tells me which class by that name should be called. CreateDB does not know and does not care where class Car is defined, it only knows that it's not defined in the same file as he is. I know what class to call and what function, but don't know how to access the class.

For example:

#in folder helpers class CreateDB(): def execute(module_name): #call the method from the class with that module_name global_dict[module_name].run_sql_create()

#in different folder classes
class Car():
   @staticmethod
   def run_sql_create():
      #do work

c = CreateDB()
c.execute("Car")

The question is, how to do this, using signals? or to cache all classes into a global dictionary and access it that way?

zPrima
  • 727
  • 1
  • 8
  • 20

2 Answers2

0

There are probably other ways to do it, but eval could be your friend here:

class Car(object):
    pass

classname = "Car"

the_class = eval(classname, globals(), locals())

This worked for me

Wolf
  • 4,254
  • 1
  • 21
  • 30
0

What you're trying to do is not well-defined. There could be several classes with the same name defined in different modules, which is perfectly valid. How would you tell which one the user wants?

I'd suggest two alternatives:

  1. pre-import all possible classes you want to support. You can then access them via globals() (e.g. cls = globals()[class_name] ; cls.execute('Car'))
  2. have the user also specify the module to import from. Then you can dynamically import the module by name (e.g. using __import__ or the imp module), then access the class defined in it. E.g. mod = __import__(mod_name) ; getattr(mod, class_name).execute('Car')
shx2
  • 61,779
  • 13
  • 130
  • 153