initialising a class by name

Steve Holden steve at
Wed Jan 14 10:09:24 CET 2009

Krishnakant wrote:
> hello all,
> I have a strange situation where I have to load initiate an instance of
> a class at run-time with the name given by the user from a dropdown
> list.
> Is this possible in python and how?
> To make things clear, let me give the real example.
> there is an inventory management system and products belong to different
> categories.
> There are predefined categories in the database and for each category
> there is a module which contains a class made out of pygtk.
> This means what class gets instantiated and displayed in the gui depends
> on the choice a user makes in the dropdown.
> Now, I could have created a list of if conditions for all the categories
> as in 
> if categorySelection == "books":
> 	Books = BookForm()
> However this is a problem because when there will be more than 100
> categories there will be that many if conditions and this will make the
> code uggly.
> so my idea is to name the class exactly after the name of the category
> so that when the user selects a category that name is used to initialise
> the instance of that class.
> So is it possible to initialise an instance of a class given its name
> from a variable?
> thanks and 
> Happy hacking.
> Krishnakant. 
You don't need to have the names of the classes related to anything in
the interface. Just use a list of classes, and have the user interface
return the correct index for each class. Then (supposing the selection
by the user is seln) use

  Books = classes[seln]()

If the classes are all in different modules, import them before creating
the list of classes.

Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC    

More information about the Python-list mailing list