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

C

Carlos Ribeiro

I'm doing some experiments with mini declarative languages (as
explained by David Mertz in
http://www-106.ibm.com/developerworks/library/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: (e-mail address removed)
mail: (e-mail address removed)
 
T

Thomas Heller

Carlos Ribeiro said:
I'm doing some experiments with mini declarative languages (as
explained by David Mertz in
http://www-106.ibm.com/developerworks/library/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
 
L

Larry Bates

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__(self, fieldname, object):
self.fields.append(object)
self.__dict__[fieldname]=object
return

def __iter__(self):
return self

def next(self):
#
# Try to get the next route
#
try: FIELD=self.fields[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
 
C

Carlos Ribeiro

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: (e-mail address removed)
mail: (e-mail address removed)
 
C

Carlos Ribeiro

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__(self)
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: (e-mail address removed)
mail: (e-mail address removed)
 
A

Andrew Dalke

Carlos said:
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.
.... def __init__(self, *args, **kwargs):
.... dict.__init__(self, *args, **kwargs)
.... self["_order"] = []
.... def __setitem__(self, 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="swordfish", password=True)

Not as clever as checking the stack trace, but probably
for the better. :)


Andrew
(e-mail address removed)
 
W

WenChen

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

**************************************************************************
 
C

Carlos Ribeiro

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: (e-mail address removed)
mail: (e-mail address removed)
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top