Using an exception to initialise a static variable in a Python function / method
Archive - Originally posted on "The Horse's Mouth" - 2010-10-13 06:52:13 - Graham Ellis
Exceptions are sometimes "sold" as a way of trapping errors - but they're more than that - they're an excellent way of trapping conditions where there isn't a valid result.
"How many people live in this house" you may ask of a function / method call, and the answer may come back as "2" or "5" ... or "0" if the house is unoccupied. But what if the function needs to say "I don't know":
• It could return a separate flag variable ... but that would need to be saved / checked every time and would require great care from the programmer to ensure it was picked up
• It could return a "cardinal value" - a result that's impossible and then have the code check for that value. Again, great care is needed by the programmer, and - worse - if a check for the values is missed by mistake it could result in the cardinal number being added in to a total or stats and letting the program proceed with wrong data
• Or it could throw an exception - and that's a neat way of ensuring, fail-safe, that the programmer making the call will allow for the "no proper result" case each and every time.
In fact ... at times exceptions are so good that they are an elegant solution to what would otherwise be messy coding. Example ...
Let's say that you're writing a Python program that needs a static variable within a function. That's a variable who's value is retained from one call to the next - the sort of thing you would want to do in an iterator where you're asking for the next item in a sequence.
You COULD initialise the variable outside the function - after you have defined the function but before you first call it. But - better - you can catch the NameError exception when you try and reference it the first time, and in the exception handling code you can initialise it.