Dynamic Class Creation

S

Steffen Schoen

(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 ?
 
T

Tom B.

Steffen Schoen said:
(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
 
D

Dominic

I have written a module which
creates classes dynamically,
but some Python tools, e.g.
PyChecker crash if they try
to analyse the source.
So be careful!

Ciao,
Dominic
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,666
Latest member
selsetu

Latest Threads

Top