ToscaWidgets: shortcut to define child fields

0 views
Skip to first unread message

Matt Good

unread,
Dec 10, 2006, 6:39:15 PM12/10/06
to TurboGears
I've started playing with ToscaWidgets is a Pylons app and I noticed a
shorter way to define the child fields for a form if you don't need to
reuse the fields in several forms.

The examples all seem to define two classes like:

class ContextFields(WidgetsList):
name = TextField()
description = TextArea()

class ContextForm(ListForm):
children = ContextFields

Which can be rewritten as:

class ContextForm(ListForm):
class children(WidgetsList):
name = TextField()
description = TextArea()

This looks nice at least for simple forms, and prevents polluting the
module's namespace with classes not intended for public use.

-- Matt Good

Alberto Valverde

unread,
Dec 11, 2006, 4:15:32 PM12/11/06
to turbo...@googlegroups.com

It sure looks nicer! (and it's intentional ;)

However, there's one small catch:

The metaclass will move the inner class to Widget._cls_chidren (this
also occurs in the two-classes syntax) and when the widget instance
is initialized widget.children won't be a WidgetList anymore but a
WidgetBunch (so children can be accessed as w.children.name,
iterated, etc...)

This is mostly an internal implementation detail... just wanted to
point it out because this kind of metaclass black-magic sometimes
seems to confuse and/or annoy some users... for example, intuition
will fail if the inner class wants to be reused. You cannot do:

class NewFields(WidgetsList):
....

fields = NewFields + ContextForm.children

but you can:

fields = NewFields() + list(ContextForm().children) # notice the
widget is instatiated

Well, bottom line: If you need to reuse fields keep the WidgetsLists
in a class by themselves and "add" them (even the class itself) as
needed

Alberto

Reply all
Reply to author
Forward
0 new messages