dynamic class instantiation

Larry Bates larry.bates at websafe.com
Mon Jan 30 16:05:50 EST 2006


Ognen Duzlevski wrote:
> Hi, I have a "language definition" file, something along the lines of:
> 
> page ::
> 	name : simple
> 	caption : simple
> 	function : complex
> 
> function ::
> 	name : simple
> 	code : simple
> 
> component ::
> 	name : simple
> 	type : simple
> 	dataset : complex
> 	
> etc.
> 
> On the other hand as input I have .xml files of the type:
> 
> <page>
> 	<name>WebPage</name>
> 	<caption>Browser Visible Caption</caption>
> 	<component>
> 		<name>Countrylist</name>
> 		<type>dropdown</type>
> 		<value>$dropdownlist</value>
> 		<function>
> 			<name>sqlSelect</name>
> 			<code>select countries 
> 			from blah into $dropdownlist</code>
> 		</function>
> 	</component>
> </page>
> 
> I have a parser that will go through the language definition 
> file and produce the following as a separate .py file:
> 
> class page(object):
> 	def __init__():
> 		self.name = None
> 		self.caption = None
> 		self.functions = []
> 
> class function(object):
> 	def __init__():
> 		self.name = None
> 		self.code = None
> 
> Now I want to use something like xml.dom.minidom to "parse" the 
> .xml file into a set of classes defined according to the "language 
> definition" file. The parse() method from the xml.dom.minidom 
> package will return a document instance and I can get the node 
> name from it. Say I got "page" as a string. How do I go about 
> instantiating a class from this piece of information? To make it 
> more obvious how do I create the page() class based on the "page" 
> string I have? I want to make this generic so for me the language 
> definition file will contain pages, functions, datasets etc. but 
> for someone else mileage will vary.
> 
> Thanks,
> Ognen

I think you should rethink this approach.  Why have 3 different
files instead of just defining everything as Python classes?
Get good baseclass definitions and use OOP inheritance to
create your specific class instances.  I think mixing XML,
language definition file (LDF), LDF to python parser is a LOT
harder (and slower) than just writing the classes outright.

-Larry Bates





More information about the Python-list mailing list