I find this design pattern comes up a lot:
try: year = int(request.GET['year'])
except: year = 0
The try
block can either fail because the key doesn't exist, or because it's not an int
, but I don't really care. I just need a sane value in the end.
Shouldn't there be a nicer way to do this? Or at least a way to do it on one line? Something like:
year = int(request.GET['year']) except 0
Or do you guys use this pattern too?
Before you answer, I already know about request.GET.get('year',0)
but you can still get a value error. Wrapping this in a try/catch block to catch the value error just means the default value appears twice in my code. Even worse IMO.