how do I make a class global?

Tom Brown brown at esteem.com
Thu Apr 27 11:47:35 EDT 2006


Hi,

I thought it would be nifty to create a class that created other classes for 
me. The method below shows what I would like to do. The problem is that the 
class the method creates is local to the method. Is it possible to make the 
class visible in the global scope so I can import the module see the 
dynamically created classes? Or do I need to generate a source file and do a 
'from tmp import *'?

def new(self, eventType, param):
	self.value += 1
	exec 'global %s; %s = %d' % (eventType, eventType, self.value)
	sl = []
	sl.append('class %sEvent(QEvent):' % eventType)
	sl.append('  def __init__(self, %s):' % param)
	sl.append('    QEvent.__init__(self, %s)' % evenType)
	sl.append('    self.%s = %s' % (param, param))
	source = '\n'.join(sl)
	co = compile(source, 'tmp.py', 'exec')
	exec co

Then, to create another event, I would just have to add another line like 
this:
e.new('ETestEvent', 'test')

Thanks,
Tom



More information about the Python-list mailing list