Dynamic Class Creation

Tom B. sbabbitt at commspeed.net
Fri Aug 6 09:39:17 EDT 2004


"Steffen Schoen" <python.noob at gmx.de> wrote in message
news:mailman.1266.1091788221.5135.python-list at python.org...
> (maybe it works better with Subject ;))
>
> Hi there,
> my problem: i have a directory, where several python modules (classes) are
> stored.
> The names of these modules arent known before runtime. Now i want to parse
> the Directory and create an instance of each class. I tried to handle this
> with
> new.instance() and new.clasobj() but this didnt really work for me. Any
> Ideas ?

You could try something like,

>>>import os
>>> import imp
>>>import glob
>>>modualnames = glob.glob('mydir\\*\\*.py')
>>>classdict = {}
>>>for i in modualnames:
>>>    flnm = file(i)
>>>    nm = os.path.splitext(os.path.basename(i))[0]
>>>    classdict[nm] = imp.load_module(nm ,flnm ,i,'')

check out the imp module in the Global Module Index.

Tom





More information about the Python-list mailing list