0

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?

2 Answers 2

6

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

Comments

3

How about something like this:

module = __import__('my_module')
if hasattr(module, 'ClassName'):
    ClassName = module.ClassName
    my_object = ClassName()

2 Comments

Looks promising, however I get, ClassName = module.ClassName AttributeError: 'module' object has no attribute 'ClassName'
@Wizzard The identifiers I wrote is just examples, and you might have to use getattr to get the classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.