[Zope] basis Zope/Python script question

Thomas B. Passin tpassin@mitretek.org
Tue, 27 Nov 2001 11:47:26 -0500


[<H.de.Wit@SFK.NL>]
>
> I write the following code repeatedly:
>
> if request.has_key('v1'):
>   v1=request.v1
> else:
>   v1=-1
>
> if request.has_key('v2'):
>   v2=request.v2
> else:
>   v2=-1
>
> etc.
>
> Is there a way to do this more efficient and clean, something like this:
>
> for reqvar in ['v1','v2','v3']:
>   if request.haskey(reqvar):
>      reqvar=request.reqvar                 #this doesn't work
>   else
>     reqvar=-1                                          # and this also
not.
>

This doesn't work because in the assignments like "reqvar=-1", the left side
is not a variable reference but a string.  There are several way you could
proceed.  You could write this:

v1=-1;v2=-1;v3=-1 # assign your default values here
vars={'v1':v1,'v2':v2,'v3':v3}

for reqvar in vars.keys():
    if request.has_key(reqvar):
        vars[reqvar]=request[reqvar]

An alternative syntax if the default is the same for all the vx's is:

v1=-1;v2=-1;v3=-1 # assign your default values here
vars={'v1':v1,'v2':v2,'v3':v3}

for reqvar in vars.keys():
    vars[reqvar]=request.get(reqvar,-1) # Returns default if key is missing

I've not tried get() on a REQUEST but assume it would work (it works for
normal Python dictionaries).

Otherwise you could use eval() or lambda functions, but I think this way is
easier.

Cheers,

Tom P