0

I have the following setup:

test.py
test\
 __init__.py
 abstract_handler.py
 first_handler.py
 second_handler.py

first_handler.py and second_handler.py contain classes with the same names that inherit from abstract_handler.

What I want to do in test.py is: given a string containing "first_handler" or any other handler class, create an object of that class.

Most solutions I found assume that the classes are in the same module (test.py), I don't know how to dynamically import the specific required class.

asked Aug 22, 2013 at 16:36

5 Answers 5

1

Use the __import__ for importing. Note that if you use submodules, you have to specify the fromlist, otherwise you get the top-level module instead. Thus

__import__('foo.bar', fromlist=['foo']).__dict__['baz_handler']()

Will call foo.bar.baz_handler()

answered Aug 22, 2013 at 16:46
Sign up to request clarification or add additional context in comments.

Comments

1

Use a dictionary for this sort of dispatching.

import first_handler
import second_handler
dispatch_dict = {
 'first': first_handler.FirstHandler
 'second': second_handler.SecondHandler
}

Now, assuming your choice is in choice_string:

instance = dispatch_dict[choice_string]()
answered Aug 22, 2013 at 16:40

Comments

0

You could probably do something like this:

from first_handler import SameName as handler1
from second_handler import SameName as handler2
handlers = {'UniqueName1': handler1,
 'UniqueName2': handler2}
instance = handlers['UniqueName1']()
answered Aug 22, 2013 at 16:40

Comments

0

This does the trick:

import abstract_handler
import first_handler
import second_handler
output = globals()['first_handler']()
answered Aug 22, 2013 at 16:43

1 Comment

Although I have the feeling this is frowned upon somehow.
0

A broad answer to the question.

To dynamically import use __import__(string) and then you'll find all the objects in .__dict__

This way you can instance based on a strings like:

c = __import__('test.first_handler').__dict__['awesomeclassname']()
answered Aug 22, 2013 at 16:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.