[Zope] Why is it so hard to do simple things?

Chris McDonough chrism@zope.com
Tue, 07 May 2002 20:18:41 -0400


John Adams wrote:
> If I was doing this in perl it'd be quite easy; I could check the query
> variable, and act on it -- but now I have to deal with things like not
> being able to even examine the variable without throwing an exception, and
> the fact that Python doesn't short-circuit blows.
> 
> i.e. You can't examine something like:
> 
> if (hasattr(request,'perm_or_temp') and request.perm_or_temp == 'P')

Python does indeed short-circuit this statement and it will work as you 
seem to expect.  Have you tried it?

In DTML, here is something that will do what I think you want.

<dtml-let button_value="REQUEST.get('perm_or_temp')">
    <INPUT TYPE='RADIO'
           NAME=perm_or_temp
           VALUE="P"
           <dtml-if "button-value=='P' or button_value==None">
           CHECKED</dtml-if>
           > Permanent
    <INPUT TYPE='RADIO'
           NAME=perm_or_temp
           VALUE="T"
           <dtml-if "button-value=='T'>
           CHECKED</dtml-if>
           > Temporary
</dtml-let>

There's a million variations on this, some better than others.  In 
Python one way to do this would be as:

button_value = context.REQUEST.get('perm_or_temp')
checked_button = {None: 'P', 'P':'P', 'T':'T'}.get(button_value)
for value in ['P', 'T']:
     checked = (value == checked_button) and ' CHECKED' or ''
     print ("<input type=radio name=perm_or_temp VALUE='%s'%s>" %
            (value, checked))
return printed

You could do something similar to this in DTML if you wanted as well. 
Since there are only a couple of possible values, it's probably easier 
just to spell it all out in this case.

I'd suggest picking up the "Learning Python" O'Reilly book to learn 
basic idioms like this.  The thing you were missing was that 
dictionary-like objects (of which REQUEST is one) have a get method that 
returns None if nothing of that key exists in the dictionary on a lookup.

-- 
Chris McDonough                    Zope Corporation
http://www.zope.org             http://www.zope.com
"Killing hundreds of birds with thousands of stones"