RepugNaNt [entries|reading|network|archive]
simont

[ userinfo | dreamwidth userinfo ]
[ archive | journal archive ]

Wed 2011-12-07 15:45
RepugNaNt
LinkReply
[identity profile] geekette8.livejournal.comWed 2011-12-07 17:07
I may be missing something, but what is wrong with:

try:
  if dictionary[key] == value:
    # do stuff
  else:
    # do other stuff
except:
  # do different stuff

?
Link Reply to this | Thread
[personal profile] simontWed 2011-12-07 17:19
It's a zillion lines long and requires dropping out of expression context to statement context!

If I was writing some complicated boolean expression along the lines of
if a<b and c==d and (dict[key]==value or other_equally_good_case):
and realised that the dictionary might not contain the key at all, then I'd much rather correct the code to
if a<b and c==d and ((key,value) in dict.viewitems() or other_equally_good_case):
than have to turn it into something like this:
try:
    tmpvar = dict[key]==value
except:
    tmpvar = False
if a<b and c==d and (tmpvar or other_equally_good_case):
There just doesn't seem to me to be any contest there.
Link Reply to this | Parent | Thread
[identity profile] fluffyrichard.livejournal.comThu 2011-12-22 07:27
Actually, that's close to what I'd probably write (though not always; context is everything, and I'd do "except KeyError" not bare except, of course). Though the reason for that is that I wouldn't call the variable tmpvar; I'd give it a meaningful name, and think of it as an opportunity to write more self-documenting code.

I don't think I've ever come across this in practice, though; normally, I just work with dicts which either don't contain None, or where None would be expected to be treated the same as the entry being missing.
Link Reply to this | Parent
[personal profile] emperorWed 2011-12-07 18:03
That should be "except KeyError:" :p

[sorry, "except:" is one of my pet python hates]
Link Reply to this | Parent
navigation
[ go | Previous Entry | Next Entry ]
[ add | to Memories ]