Python declarative

Terry Reedy tjreedy at udel.edu
Wed Jan 15 17:58:05 EST 2014


On 1/15/2014 12:33 PM, Chris Angelico wrote:
> On Thu, Jan 16, 2014 at 4:02 AM, Sergio Tortosa Benedito
> <sertorbe at gmail.com> wrote:
>> Hi I'm developing a sort of language extension for writing GUI programs
>> called guilang, right now it's written in Lua but I'm considreing Python
>> instead (because it's more tailored to alone applications). My question
>> it's if I can achieve this declarative-thing in python. Here's an
>> example:
>>
>> Window "myWindow" {
>>          title="Hello world";
>>          Button "myButton" {
>>                  label="I'm a button";
>>                  onClick=exit
>>          }
>> }
>> print(myWindow.myButton.label)
>
> Probably the easiest way to do that would be with dictionaries or
> function named arguments. It'd be something like this:
>
> myWindow = Window(
>      title="Hello World",
>      myButton=Button(
>          label="I'm a button",
>          onClick=exit
>      )
> )
> print(myWindow.myButton.label)

This is exactly what I was going to suggest.

> For this to work, you'd need a Window class that recognizes a number
> of keyword arguments (eg for title and other attributes), and then
> takes all other keyword arguments and turns them into its children.

I would make the required args positional-or-keyword, with or without a 
default. Something like (tested)

class Window:
     def __init__(self, title, *kwds)  # or title='Window title'
         self.title = title
         self.__dict__.update(kwds)

class Button:
     def __init__(self, label, **kwds):
         self.label = label
         self.__dict__.update(kwds)

<add Chris' code above>
 >>>
I'm a button

> Possible, but potentially messy; if you happen to name your button
> "icon", it might be misinterpreted as an attempt to set the window's
> icon, and cause a very strange and incomprehensible error.

Puns are always a problem with such interfaces. Validate the args as 
much as possible. An icon should be a bitmap of appropriate size. 
Optional args should perhaps all be widgets (instances of a Widget 
baseclass).

-- 
Terry Jan Reedy




More information about the Python-list mailing list