4

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?

2 Answers 2

7

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

1 Comment

Hi Matt, when MyPythonClass1 is defined in another module, we'll need to import it first, right? Can we avoid that, as importing the class will import all the class' imports, which might be undesirable?
0

If module is the module the class named classname lives in, you can get the class object using

class_ = getattr(module, classname)

(If the class lives in the main module, use import __main__ to get a module object for this module.)

To look up the class in the current module's global scope, use

class_ = globals()[classname]

I think a static dictionary as in Matt's answer is the better solution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.