basis Zope/Python script question
Hello, 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. Het vriendelijke groeten, Hans de Wit Stichting Farmaceutische Kengetallen Postbus 30460 2500 GL DEN HAAG Tel. 070-3737448 Fax 070-3737445
Hi Het, How about: v1, v2, v3 = map(request.get, ['v1','v2','v3'], [-1]*3) -steve On Tuesday, November 27, 2001, at 09:58 AM, H.de.Wit@SFK.NL wrote:
Hello,
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.
Het vriendelijke groeten,
Hans de Wit Stichting Farmaceutische Kengetallen Postbus 30460 2500 GL DEN HAAG Tel. 070-3737448 Fax 070-3737445
_______________________________________________ Zope maillist - Zope@zope.org http://lists.zope.org/mailman/listinfo/zope ** No cross posts or HTML encoding! ** (Related lists - http://lists.zope.org/mailman/listinfo/zope-announce http://lists.zope.org/mailman/listinfo/zope-dev )
[<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
participants (3)
-
H.de.Wit@SFK.NL -
Steve Spicklemire -
Thomas B. Passin