Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically call python-class defined in config-file

Tags:

python

I have a config.cfg which I parse using the python-module ConfigParser. In one section I want to configure assignments of the form fileextension : ClassName. Parsing results in the following dictionary:

types = {
  "extension1" : "ClassName1",
  "extension2" : "ClassName2"
}

EDIT: I know I can now do:

class_ = eval(types[extension])
foo = class()

But I was given to understand that eval is evil and should not be used.

Do you know a nicer way to dynamically configure which file-extension results in which class?

like image 204
florianletsch Avatar asked Sep 02 '25 16:09

florianletsch


1 Answers

You could use eval, if the class name in the config file exactly matches the class names in your python code (and if the classes are in scope!), but ..... eval is evil (a coincidence that there's only one letter difference? I think not!)


A safer way to do it would be to add an extra dictionary that maps from configuration class name to python class name. I'd do this because:

  • configuration files don't have to know about your code's names
  • can change config files without changing code and vice versa
  • it avoids eval

So it'd look something like:

mappingDict = {"ClassName1" : MyPythonClass1, 
               "ClassName2" : MyPythonClass2, ... }
# keys are strings, values are classes

Then you perform a lookup using the value from the config file:

myClassName = types['extension1']
myClass = mappingDict[myClassName]
like image 53
Matt Fenwick Avatar answered Sep 04 '25 06:09

Matt Fenwick