473,757 Members | 10,708 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

An attempt to use a python-based mini declarative language for formdefinition

I'm doing some experiments with mini declarative languages (as
explained by David Mertz in
http://www-106.ibm.com/developerwork...y/l-cpdec.html) in Python,
with the intention to use it as the mechanism to define data entry
forms. My final goal is to have a simple approach to automatic
generation of visual interfaces. The complete framework is rather big,
so let's us focus at this specific problem.

-- I would like to describe my data entry forms with plain Python
code. I don't want to use XML, dicts or other data-driven solution;
not because I don't like it, not because I don't know about it, only
because I want to try a different approach.

-- This is a simple code snippet of the intended form declaration:

class UserForm(Form):
nickname = TextBox(length= 15, default="")
password = TextBox(length= 10, default="", password=True)
name = TextBox(length= 40, default="")

It's actually based to some extent on Ian Bicking's sqlobject library,
that uses a similar approach to build entity definitions. But there's
a catch: the class constructor receives a dict, and has no way to tell
the original ordering of the attributes in the original class. The
field names are passed in an arbitrary ordering, due to the use of the
dict mapping.

-- I've tried using metaclasses or other similar magic; I've read the
tutorials, tried some code, and read sqlobject own implementation.
This is not a problem for sqlobject, because the order of the columns
in the database is totally isolated from the object representation.
But in my case, it is a problem, because I need the fields to be in
the correct order in the display.

My question is, there is any way to retrieve the class attributes in
the order they were declared? I could not find any; __setattr__ won't
work because the dict is constructed using the native dict type before
__new__ has a chance at it. Is there anything that I'm overlooking?
--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #1
7 1576
Carlos Ribeiro <ca********@gma il.com> writes:
I'm doing some experiments with mini declarative languages (as
explained by David Mertz in
http://www-106.ibm.com/developerwork...y/l-cpdec.html) in Python,
with the intention to use it as the mechanism to define data entry
forms. My final goal is to have a simple approach to automatic
generation of visual interfaces. The complete framework is rather big,
so let's us focus at this specific problem.

-- I would like to describe my data entry forms with plain Python
code. I don't want to use XML, dicts or other data-driven solution;
not because I don't like it, not because I don't know about it, only
because I want to try a different approach.

-- This is a simple code snippet of the intended form declaration:

class UserForm(Form):
nickname = TextBox(length= 15, default="")
password = TextBox(length= 10, default="", password=True)
name = TextBox(length= 40, default="")

It's actually based to some extent on Ian Bicking's sqlobject library,
that uses a similar approach to build entity definitions. But there's
a catch: the class constructor receives a dict, and has no way to tell
the original ordering of the attributes in the original class. The
field names are passed in an arbitrary ordering, due to the use of the
dict mapping.

-- I've tried using metaclasses or other similar magic; I've read the
tutorials, tried some code, and read sqlobject own implementation.
This is not a problem for sqlobject, because the order of the columns
in the database is totally isolated from the object representation.
But in my case, it is a problem, because I need the fields to be in
the correct order in the display.

My question is, there is any way to retrieve the class attributes in
the order they were declared? I could not find any; __setattr__ won't
work because the dict is constructed using the native dict type before
__new__ has a chance at it. Is there anything that I'm overlooking?


No, there is no way. But there is a trick you can use (I've played with
stuff like this, in a different context, in the past): You can use an
instance variable or global in the TextBox callable, that is incremented
on each call. This counter is somehow attached to the object that
TextBox returns, and lets you order these objects afterwards. Makes
sense?

Thomas
Jul 18 '05 #2
You may can write your own __setattr__ method.
That way you can keep track of the order of
the fields yourself.

class UserForm(Form):
def __init__(self):
self.fields=[]
self.next_index =0 # Index pointer for next method
self.nickname = TextBox(length= 15, default=""))
self.password = TextBox(length= 10, default="", password=True))
self.name = TextBox(length= 40, default="")
return

def __setattr__(sel f, fieldname, object):
self.fields.app end(object)
self.__dict__[fieldname]=object
return

def __iter__(self):
return self

def next(self):
#
# Try to get the next route
#
try: FIELD=self.fiel ds[self.next_index]
except:
self.next_index =0
raise StopIteration
#
# Increment the index pointer for the next call
#
self.next_index +=1
return FIELD
self.fields list will contain the fields in the
order they were defined. self.__dict__ contains
them in dictionary that __getattr__ will reference
for indexed lookup. I added __iter__ and next
methods so you can easily loop over all the fields.
Not tested and just one of
many methods.

Larry Bates

"Carlos Ribeiro" <ca********@gma il.com> wrote in message
news:ma******** *************** *************** @python.org...
I'm doing some experiments with mini declarative languages (as
explained by David Mertz in
http://www-106.ibm.com/developerwork...y/l-cpdec.html) in Python,
with the intention to use it as the mechanism to define data entry
forms. My final goal is to have a simple approach to automatic
generation of visual interfaces. The complete framework is rather big,
so let's us focus at this specific problem.

-- I would like to describe my data entry forms with plain Python
code. I don't want to use XML, dicts or other data-driven solution;
not because I don't like it, not because I don't know about it, only
because I want to try a different approach.

-- This is a simple code snippet of the intended form declaration:

class UserForm(Form):
nickname = TextBox(length= 15, default="")
password = TextBox(length= 10, default="", password=True)
name = TextBox(length= 40, default="")

It's actually based to some extent on Ian Bicking's sqlobject library,
that uses a similar approach to build entity definitions. But there's
a catch: the class constructor receives a dict, and has no way to tell
the original ordering of the attributes in the original class. The
field names are passed in an arbitrary ordering, due to the use of the
dict mapping.

-- I've tried using metaclasses or other similar magic; I've read the
tutorials, tried some code, and read sqlobject own implementation.
This is not a problem for sqlobject, because the order of the columns
in the database is totally isolated from the object representation.
But in my case, it is a problem, because I need the fields to be in
the correct order in the display.

My question is, there is any way to retrieve the class attributes in
the order they were declared? I could not find any; __setattr__ won't
work because the dict is constructed using the native dict type before
__new__ has a chance at it. Is there anything that I'm overlooking?
--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com

Jul 18 '05 #3
On Wed, 22 Sep 2004 20:04:21 +0200, Thomas Heller <th*****@python .net> wrote:
No, there is no way. But there is a trick you can use (I've played with
stuff like this, in a different context, in the past): You can use an
instance variable or global in the TextBox callable, that is incremented
on each call. This counter is somehow attached to the object that
TextBox returns, and lets you order these objects afterwards. Makes
sense?


I think that it does. Actually, I had a pretty much more ellaborate
idea that rely on a *lot* of introspection for the same effect. It's
not for the faint of heart :-)

It goes like this: inside the TextBox constructor, raise an exception,
capture the stack frame, and check from where was it called. I think
there's enough information at this point to order the elements. As I
said, not for the faint of heart, and it smells like a terrible hack.

I'll check this and other similar ideas. Thanks again,
--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #4
On Wed, 22 Sep 2004 13:10:00 -0500, Larry Bates <lb****@swamiso ft.com> wrote:
You may can write your own __setattr__ method.
That way you can keep track of the order of
the fields yourself.


Larry,

I may have made a mistake on my own code, but __setattr__ would not
work for me; I'm creating my instances through a metaclass, and I'm
using class attributes for the fields.

In your example the form fields are instance attributes. In this case,
I agree it works. But as I said -- I was testing if I could make it
work using class attributes and metaclasses. I think that the
resulting code is much cleaner (after all black magic is done and
hidden from the user, that is). Compare:

1) using class attributes

class UserForm(Form):
nickname = TextBox(length= 15, default="")
password = TextBox(length= 10, default="", password=True)
name = TextBox(length= 40, default="")

2) using instance atttributes

class UserForm(Form):
def __init__(self):
Form.__init__(s elf)
self.nickname = TextBox(length= 15, default=""))
self.password = TextBox(length= 10, default="", password=True))
self.name = TextBox(length= 40, default="")

Others may think that's a small difference, but if I could choose
between both approaches, I would surely pick (1).

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #5
Carlos Ribeiro wrote:
I may have made a mistake on my own code, but __setattr__ would not
work for me; I'm creating my instances through a metaclass, and I'm
using class attributes for the fields.


I tried too, though not using metaclasses.
class StoreOrder(dict ): .... def __init__(self, *args, **kwargs):
.... dict.__init__(s elf, *args, **kwargs)
.... self["_order"] = []
.... def __setitem__(sel f, k, v):
.... dict.__setitem_ _(self, k, v)
.... self["_order"].append(k)
.... x = StoreOrder()
x["a"] = 9
x["b"] = 10
x {'a': 9, '_order': ['_order', 'a', 'b'], 'b': 10} class Form: .... pass
.... Form.__dict__ = StoreOrder()
Form.__dict__ {'_order': ['_order']} Form.a = 9
Form.__dict__ {'a': 9, '_order': ['_order']} Form.__dict__["b"] = 10
Form.b 10
What happens is that class assignment sets the
class __dict__ via PyDict_SetItem and not
through the generic mapping interface. In
essence it does

dict.__setitem_ _(self.__dict__ , "new class var", val)
instead of
setitem(self.__ dict__, "new class var", val)

Therefore I don't think it's possible to do what
you want. There's no way to interpose your own
code in class variable assignment.

Here's a way to implement the suggestion of
Thomas Heller's.

import itertools
order_gen = itertools.count ().next

class Counted(object) :
def __init__(self):
self._order = order_gen()

class TextBox(Counted ):
def __init__(self, length, default, password = False):
Counted.__init_ _(self)
self.length = length
self.default = default
self.password = password

class Form:
nickname = TextBox(length= 15, default="")
password = TextBox(length= 10, default="swordf ish", password=True)
Form.nickname._ order 0 Form.password._ order 1


Not as clever as checking the stack trace, but probably
for the better. :)
Andrew
da***@dalkescie ntific.com
Jul 18 '05 #6
Hi

I have done scripts to generate web form and the rest xml, content
template at once

here is the url
http://newped.auckland.ac.nz/python/idevice_template

Currently, the save function only generate files in a template directory

That editor's goal is to allow none techie people to generate their
instructional devices( form ) on their own will and can be plugged into
eXe for use without further coding needs.

Don't know is this somewhat similar to what you want
the code itself is nothing special, it uses javascript dom and python
text processing.

*************** *************** *************** *************** **************
Later, we will put a help box & extra info ( for advanced user to put
style, tags info) for a field,

This is a tool we will use in an opensource project
https://eduforge.org/projects/exe/

still at pre-planning stage, but there is a proof-of-concept to play
around -- see the idevices list, those can be generated by the idevice
editor
http://newped.auckland.ac.nz/python/eXe/start.pyg

*************** *************** *************** *************** **************

There should be some way to pass the "location". If you solve this,
you got your answer (of course, passing the "location" is not trivial,
that's why every GUI toolkit has it own approach).

That's *exaclty* the root of my problems. I don't want to specify
positioning; I only want to use *relative positioning* for everything,
working as automatically as possible. Will it work for all situations?
I'm not sure. But I think it's worth investigating.

What I intend to do is to borrow some of the layout techniques defined
by CSS+DHTML. It is *much* more complex that this, but it basically
works by formatting "block level" and "inline elements" elements
relatively to each other. You can give hints as to the relative
positioning -- absolute, relative, floating to the left, floating to
the right, and stuff like that. The layout engine positions everything
according to the constraints. If the engine doesn't support advanced
layout, it simply falls back to a simple sequence of entries according
to the original text flow.

There are two reasons behnd my choice:

-- there is a lot of knowledge today about how to make good interfaces
using CSS. It's faster to develop and is more flexible regarding
different engines and platforms than to rely on absolute positioning
(as conventional GUI builders do)

-- it makes *much* easier to use the same form definition on native
GUIs and web-based ones. My goal is to be able to build a wxPython
dialog or a web form from the same description.

That's why I can't give positioning hints, at least for now. But I
could include relative ordering information; for example, an arbitrary
tag number. But doing this I would defeat my objective of clarity of
design.


Jul 18 '05 #7
On 23 Sep 2004 14:18:25 +1200, WenChen <w.***@auckland .ac.nz> wrote:
Hi

I have done scripts to generate web form and the rest xml, content
template at once

here is the url
http://newped.auckland.ac.nz/python/idevice_template


Yes, its closely related to what I'm trying to do, but still its
different, because I want to be able to write the specification of the
data entry form as a Python class that can in turn be converted into a
HTML representation. BTW, I solved most of the issues that were
barring my progress, and I think I may be able to have something
working quite fast now.

Thanks for the pointer,

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #8

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

Similar topics

41
2870
by: John Marshall | last post by:
How about the following, which I am almost positive has not been suggested: ----- class Klass: def __init__(self, name): self.name = name deco meth0: staticmethod def meth0(x):
7
1547
by: Robin Siebler | last post by:
I want to use filecmp.dircmp, but it only prints to the screen, there is no way to capture the output. So I thought that I should simply be able to subclass it to return a list (Danger! Danger, Will! Simple and Subclass should never be used in the same sentence!). However, my first attempt (pathetic as it may be), results in an error that I don't understand. Obviously, I'm doing something wrong, but what? I'm using Python 2.2.3 and the...
3
14127
by: John Ortt | last post by:
> I have a table of dates in ascending order but with varying intervals. I > would like to create a query to pull out the date (in field 1) and then pull > the date from the subsequent record (and store it in field 2). > > I would like to run a query that returns all the data in the table plus the > record number, in a similar sense to the getuser() command to get the User's > Identity, I would like a GetRecord() command.
1
2618
by: Bryan Martin | last post by:
Using udp sockets inside a class called by ASP.NET By impersonating you can use a TCP socket from a external class and call it from a ASP.NET page. However, changing the socket type to UDP and binding it to a port throws an error "An attempt was made to access a socket in a way forbidden by its access permissions". I tried all the methods I knew of to get this to work such as... ASPNET added the account to the local administrators...
2
5212
by: Brent Burkart | last post by:
Below is the error I am receiving. I have checked SQL Profiler and it is receiving the correct query which runs fine in Query Analyzer. Any ideas? Server Error in '/lockinsheet' Application. ---------------------------------------------------------------------------- ---- Invalid attempt to read when no data is present. Description: An unhandled exception occurred during the execution of the current web request. Please review the...
3
8627
by: Freddie | last post by:
hi, i try to get the asp.net 2.0 security controls to work with SQL Server 2005 Dev RTM, this is my connetion string in mashine.config <connectionStrings> <add name="LocalSqlServer" connectionString="data source=.;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=false;" providerName="System.Data.SqlClient" />
2
9758
by: Dennis | last post by:
I'm getting the following problem occasionally...the application will work perfectly well for a period of time and then this pops up. I have tried turning off the default proxy in the web.config which I had seen on other posts but that did not solve the problem. Any assistance or ideas would be appreciated Thanks
3
6530
by: divsTiw | last post by:
I want to populate combo box with data from OracleDataReader , but "Invalid attempt to read when no data is present." is thrown. there are two rows returned , then too why such error. plzzz share ur knowledge to help me out with this probs. my code is as below,
4
3035
by: Colin J. Williams | last post by:
The readme.txt has: All you need to do is open the workspace "pcbuild.sln" in Visual Studio, select the desired combination of configuration and platform and eventually build the solution. Unless you are going to debug a problem in the core or you are going to create an optimized build you want to select "Release" as
2
3410
by: Colin J. Williams | last post by:
Using >easy_install -v -f http://code.enthought.com/enstaller/eggs/source enthought.traits The result is: .... many lines ....
0
9489
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...
1
9885
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
9737
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
8737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7286
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6562
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2698
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.