Reputation: 12702
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?
Upvotes: 0
Views: 2329
Reputation: 9041
Try this:
file_name = 'lex_parser'
class_name = 'LexParser'
Parser = getattr(__import__(file_name), class_name)
Note that file_name
must 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:
import sys
file_name = 'parsers.lex_parser'
class_name = 'LexParser'
__import__(file_name)
Parser = getattr(sys.modules[file_name], class_name)
This will work in both cases and is recommeded by the __import__
function documentation.
In both examples Parser
is a class which you have to instantiate as normally:
parser = Parser()
Upvotes: 6
Reputation: 409166
How about something like this:
module = __import__('my_module')
if hasattr(module, 'ClassName'):
ClassName = module.ClassName
my_object = ClassName()
Upvotes: 3