An attempt to use a python-based mini declarative language forformdefinition

Robert Brewer fumanchu at amor.org
Wed Sep 22 15:40:59 EDT 2004


Larry Bates wrote:
> 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.

You're going to run into a problem with that approach: when you set
self.fields in __init__, it will also call __setattr__ and fail, because
__setattr__ references 'fields' but you haven't defined it yet. You can
work around that special case, but it's going to continue to bite you
when you add attributes which you don't want indexed. I have a gut
feeling that a custom descriptor would solve that, but don't have time
to lay it all out. :(


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list