Omar Tarabai
Omar Tarabai

Reputation: 373

Python dynamic class name creation

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.

Upvotes: 0

Views: 241

Answers (5)

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()

Upvotes: 1

Paolo Casciello
Paolo Casciello

Reputation: 8202

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']()

Upvotes: 0

Brionius
Brionius

Reputation: 14098

This does the trick:

import abstract_handler
import first_handler
import second_handler

output = globals()['first_handler']()

Upvotes: 0

g.d.d.c
g.d.d.c

Reputation: 47988

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']()

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599580

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]()

Upvotes: 1

Related Questions