[Tutor] if value not in dictionary, do a?

Hugo Arts hugo.yoshi at gmail.com
Fri Mar 25 17:24:07 CET 2011

On Fri, Mar 25, 2011 at 5:11 PM, Robert Sjoblom
<robert.sjoblom at gmail.com> wrote:
> -- Hugo Arts wrote --
>>Why are you asking for the user to enter a key? you're iterating over
>>all keys in the dictionary, so there's no need to ask the user for
>>keys, you already know them. Why not do this:
>>b = int(input("Enter value for key %s: " % key))
>>dictionary[key] = b
> I have a great answer to that, actually. I simply forgot that you
> could. I _knew_ that there was a better way of doing what I was trying
> to accomplish, but I needed the user to know which key was being
> entered, and I completely forgot about %s.
>>* don't use a blank except. *ever*. If you really want to catch
>>everything, do "except Exception:" otherwise, catch what you expect to
>>be thrown in this case, "except KeyError"
> I received your email just as I left my computer, and didn't want to
> type out an answer on my phone (because smartphones aren't smart
> enough for that yet), and my first reaction was "why?" followed by "I
> need my program to continue even if I get the errors at this part, so
> why?" I soon realized that catching all errors would mean never seeing
> the errors you might not foresee. I know that I could get either
> ValueError or KeyError, but there could be something else somewhere
> else in the code that could send an error (unlikely as it is) down
> that path and with a blank except I would never actually see that
> happen. Am I somewhat close to the real reason why?

Pretty much. The point here is that blank exceptions hide errors, and
therefore bugs, in your code. Suppose you make a typo inside the
exception, "dicionary" for example. Normally, that is not a very big
deal, because python will see a name that doesn't exist, and complain.
But how will it complain? By throwing a NameError! And inside that try
statement, te blank except will swallow the NameError quite happily
and moving along, leaving you clueless as to what actually went wrong.

It's not a big deal in small programs like this, but in big ones, you
won't have a clue, and a simple typo turns into a frustrating bughunt.

More information about the Tutor mailing list