I have code like this:
try:
request=parse_request
except:
print "cannot parse your malformed request"
exit()
else:
try:
fh=a_factory_function()
except:
print "cannot create object"
else:
if request['operation']=='search':
pass
elif request['operation']=='more_like_this':
pass
elif request['operation']=='list_files':
pass
elif request['operation']=='update':
pass
else:
print 'unsupported operation'
In present form it has two levels of indentation
- parse a request
- the factory function to generate an object to process the request
I can easily imagine this getting to 4 levels and becoming too complex for our puny reasoning. Is there a Pythonic way to flatten the indentation and make it “linear”?
Unless I’m misinterpreting your code, you’re using the
elseclause of thetrystatement for normal processing. In effect, you’re simulating return code error handling with exceptions. Why not do this?There is a good answer by Blair Conrad here on StackOverflow that explains why you might want to use an
elseclause.