473,657 Members | 2,659 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dynamic class instantiation

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>Browse r Visible Caption</caption>
<component>
<name>Countryli st</name>
<type>dropdow n</type>
<value>$dropdow nlist</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
Jan 30 '06 #1
10 2667
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>Browse r Visible Caption</caption>
<component>
<name>Countryli st</name>
<type>dropdow n</type>
<value>$dropdow nlist</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
Jan 30 '06 #2
Larry Bates <la*********@we bsafe.com> wrote:
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.


Hi Larry,

here is the whole story. I have a database (postgres) xml "transforme r"
and substitution engine. It is written entirely in plpgsql and the whole
environment works something like this. Someone writes an xml file that
defines a web page. This xml file is then fed into the database at the
time of development. Now at runtime a mod_python apache webapp makes a
request for a certain page. Its xml form is retrieved from the database
and a lot of data substitution goes on. Also parts of the page are "masked"
out by the database engine based on the "level" of the person requesting
the page. The "transforme d and substituted" xml is then spit back to the
webapp which now applies an xml->html transformation and presents the
final result to the user. So, I want people to be able to "define" their
own "language" when it comes to page definitions. And instead of rewriting
the xml file parser I want to be able to generate the parser.

Thanks,
Ognen
Jan 30 '06 #3
Ognen Duzlevski wrote:
Larry Bates <la*********@we bsafe.com> wrote:
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.


Hi Larry,

here is the whole story. I have a database (postgres) xml "transforme r"
and substitution engine. It is written entirely in plpgsql and the whole
environment works something like this. Someone writes an xml file that
defines a web page. This xml file is then fed into the database at the
time of development. Now at runtime a mod_python apache webapp makes a
request for a certain page. Its xml form is retrieved from the database
and a lot of data substitution goes on. Also parts of the page are "masked"
out by the database engine based on the "level" of the person requesting
the page. The "transforme d and substituted" xml is then spit back to the
webapp which now applies an xml->html transformation and presents the
final result to the user. So, I want people to be able to "define" their
own "language" when it comes to page definitions. And instead of rewriting
the xml file parser I want to be able to generate the parser.

Thanks,
Ognen


Well you certainly can do that, but why invent a new language to define
the pages instead of just using Python directly? I did an application
a few years ago that sounds a little like what you describe and now
wish I had not spent so much time doing Text File->Python transforma-
tions. The logic got pretty ugly and extending things was rather
involved. It wasn't until I started using ReportLab that I began to
"see the light" on just keeping everything in Python and inheriting
from base classes and extending.

If you want to define a Python class, the best way to do that is to
use Python from the outset. I probably don't completely understand
what you want to do, but thought I'd at least put in my 2-cents worth.

Regards,
Larry
Jan 30 '06 #4
Ognen Duzlevski wrote:
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 = []

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?


Use getattr().

If the definition of page is in my_objects.py, and that file is on the
Python search path, you can use
import my_module
cls = getattr(my_modu le, 'path')
instance = cls()

to create an instance of my_module.path.

Kent
Jan 30 '06 #5
Kent Johnson <ke**@kentsjohn son.com> wrote:
Ognen Duzlevski wrote:
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?
Use getattr().


Hi Kent, this is exactly what I was looking for. I can't believe I didn't think
of getattr() myself! ;(

Cheers,
Ognen
Jan 31 '06 #6
Ognen Duzlevski wrote:
Kent Johnson <ke**@kentsjohn son.com> wrote:
Ognen Duzlevski wrote:
> 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?

Use getattr().


Hi Kent, this is exactly what I was looking for. I can't believe I didn't think
of getattr() myself! ;(


However, remember that this solves your problem just temporarily.

Your main problem is still a deep design failure. Code generators are
relicts, hard to maintain, and usually just plain ugly. Your application
isn't that special.

I'm sure you could replace 2/3 of your code with something much simpler
(and shorter!) just by not inventing a new language and using the power
of Python instead.

People often think that a new language simplifies their problem, and that
code generation saves work. However, a the code of the code generator has
to be maintained, too! That's what most people are realizing too late.
Also, simple class inheritance, closures and similar mechanisms save a
lot of work, too, they do their job even better than a code generator,
and they are a charm to maintain.

Even the "magic" (AKA meta-classes :-)) may be hard, but it's usually a
much simpler and cleaner approach than a code generator.

Don't generate Python code. Python is neither Java nor C, it's dynamic!
Greets,

Volker

--
Volker Grabsch
---<<(())>>---
\frac{\left|\va rtheta_0\times\ {\ell,\kappa\in \Re\}\right|}{\ sqrt
[G]{-\Gamma(\alpha)\ cdot\mathcal{B} ^{\left[\oint\!c_\hbar\ right]}}}
Feb 1 '06 #7
Volker Grabsch <vo************ @v.notjusthosti ng.com> wrote:
Ognen Duzlevski wrote:
Kent Johnson <ke**@kentsjohn son.com> wrote:
Ognen Duzlevski wrote:
> 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?
Use getattr().


Hi Kent, this is exactly what I was looking for. I can't believe I didn't think
of getattr() myself! ;(

However, remember that this solves your problem just temporarily. Your main problem is still a deep design failure. Code generators are
relicts, hard to maintain, and usually just plain ugly. Your application
isn't that special. I'm sure you could replace 2/3 of your code with something much simpler
(and shorter!) just by not inventing a new language and using the power
of Python instead.


Hi Volker,

I appreciate your comments. Basically, the reason why this code generator
exists is the fact that I do not want to hard-code the resulting xml in
any way. The users of the web/db framework of which this solution is part of
might like the "web page" definition I offer them, but, some might want to extend it.
While dom allows me to traverse an xml hierarchy - it does not allow me to
give "meaning" to the tags. The only way to do that (for me) is to represent
the tags as classes with containers containing other classes (tags) and so on. Since
I do not know ahead of time what the tags will be - I need to generate the code
to actually handle them.

Can you suggest a better approach or did you already do that and I just missed
it? :)

Cheers,
Ognen
Feb 1 '06 #8
Ognen Duzlevski wrote:
Volker Grabsch <vo************ @v.notjusthosti ng.com> wrote:
I'm sure you could replace 2/3 of your code with something much simpler
(and shorter!) just by not inventing a new language and using the power
of Python instead.

Hi Volker,

I appreciate your comments. Basically, the reason why this code generator
exists is the fact that I do not want to hard-code the resulting xml in
any way. The users of the web/db framework of which this solution is part of
might like the "web page" definition I offer them, but, some might want to extend it.
While dom allows me to traverse an xml hierarchy - it does not allow me to
give "meaning" to the tags. The only way to do that (for me) is to represent
the tags as classes with containers containing other classes (tags) and so on. Since
I do not know ahead of time what the tags will be - I need to generate the code
to actually handle them.

Can you suggest a better approach or did you already do that and I just missed
it? :)


Instead of generating Python code and importing it, you could create the
classes directly. You would still have your own language but no code
generator.

For a very simple example, you could have a base class that initializes
attributes from a class dictionary:
class DynamicInits(ob ject):
def __init__(self):
self.__dict__.u pdate(self.init s)

and a simple factory function that creates a subclass with an
appropriate dict of initializers:
def classFactory(na me, initializers):
return type(name, (DynamicInits,) , {'inits' : initializers})

In your original post you show this class:
class page(object):
def __init__():
self.name = None
self.caption = None
self.functions = []

With the above definitions, an equivalent class is created by calling
page = classFactory( 'page', { 'name' : None, 'caption': None,
'functions' : []} )

Kent
Feb 2 '06 #9
Kent Johnson <ke**@kentsjohn son.com> wrote:
Ognen Duzlevski wrote:
Can you suggest a better approach or did you already do that and I just missed
it? :)
With the above definitions, an equivalent class is created by calling
page = classFactory( 'page', { 'name' : None, 'caption': None,
'functions' : []} )


Beautiful. Thank you very much.

Cheers,
Ognen
Feb 2 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2474
by: Drew McCormack | last post by:
I have a C++ template class which contains a static variable whose construction registers the class with a map. Something like this: template <typename T> class M { static Registrar<M> registrar; }; The constructor of Registrar does the registering when it is initialized.
3
8249
by: Patrick Guio | last post by:
Hi, I have trouble to compile the following piece of code with g++3.4 but not with earlier version // Foo.h template<typename T> class Foo { public:
3
2197
by: Jakob Lithner | last post by:
I have searched the news groups on similar subjects, but haven't found anything adequate for my need .... To save much duplication of code I would like to create a baseclass that takes a SQL-Select-string and a type as parameters. It will then return a collection of objects of the specified type. (I have ~30 object types that will be fetched in exactly the same way from one table each). Dynamic parsing works fine using the Reflection...
60
10140
by: Peter Olcott | last post by:
I need to know how to get the solution mentioned below to work. The solution is from gbayles Jan 29 2001, 12:50 pm, link is provided below: > http://groups.google.com/group/comp.lang.c++/msg/db577c43260a5310?hl > >Another way is to create a one dimensional array and handle the >indexing yourself (index = row * row_size + col). This is readily >implemented in template classes that can create dynamically allocated >multi-dimensional...
23
3841
by: mark.moore | last post by:
I know this has been asked before, but I just can't find the answer in the sea of hits... How do you forward declare a class that is *not* paramaterized, but is based on a template class? Here's what I thought should work, but apparently doesn't: class Foo; void f1(Foo* p)
2
1744
by: Mark P | last post by:
Still being relatively new to C++ I like to go back to review and rethink old designs to see where I could do things better. The issue I'm currently pondering is static vs. dynamic polymorphism, or equivalently in my case, templates vs abstract base classes. Let me be concrete. I have a class for performing a geometry operation which takes a collection of line segments and breaks them into minimal nonintersecting subsegments. I wrote...
13
1854
by: jerryau | last post by:
Hi, I am trying to dynamically create object instances based on a string class name, and then I need to dynamically set values to these objects, but I have no idea how to do this in C#. Here is the example of what I need to do: ******Dog.cs****** namespace MySystem {
8
2139
by: Ole Nielsby | last post by:
I want to create (with new) and delete a forward declared class. (I'll call them Zorgs here - the real-life Zorks are platform-dependent objects (mutexes, timestamps etc.) used by a cross-platform scripting engine. When the scripting engine is embedded in an application, a platform-specific support library is linked in.) My first attempt goes here: ---code begin (library)---
4
2485
by: yuanhp_china | last post by:
I define a class in A.h: template <class Tclass A{ public: void get_elem( const T&) ; };
0
8385
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8821
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8723
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8502
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8602
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1941
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.