With my python application, I have 40 modules (classes) which contain a parser for some text. In my function I only want to instanciate and use a particular module. These are all sorted in the database.
I am at the point now where I know my parser, and have both the python file name and class I want to import and create
However…. How do you actually do this in python?
eg;
file_name = 'lex_parser'
class_name = 'LexParser'
how can I do….
from {file_name} import {class_name}
Parser = {class_name}()
Follow what I mean?
Try this:
Note that
file_namemust not contain.py.This won’t work if the module is within a package because
__import__would return the top level package. In that case you can do this:This will work in both cases and is recommeded by the
__import__function documentation.In both examples
Parseris a class which you have to instantiate as normally: