Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Frequently repeated try/except in Python

Tags:

Firstly, I'm not sure if my approach is proper, so I'm open to a variety of suggestions.

If try/except statements are frequently repeated in code, are there any good ways to shorten them or avoid fully writing them out?

try:     # Do similar thing     os.remove('/my/file') except OSError, e:     # Same exception handing     pass  try:     # Do similar thing     os.chmod('/other/file', 0700) except OSError, e:     #Same exception handling     pass 

For example, for one line actions you could define a exception handling wrapper and then pass a lambda function:

def may_exist(func):     "Work with file which you are not sure if exists."""     try:         func()     except OSError, e:         # Same exception handling         pass  may_exist(lambda: os.remove('/my/file')) may_exist(lambda: os.chmod('/other/file', 0700)) 

Does this 'solution' just make things less clear? Should I just fully write out all the try/except statements?

like image 207
sutre Avatar asked Aug 18 '11 13:08

sutre


1 Answers

The best way to abstract exception handling is with a context manager:

from contextlib import contextmanager @contextmanager def common_handling():     try:         yield     finally:         # whatever your common handling is 

then:

with common_handling():     os.remove('/my/file')  with common_handling():     os.chmod('/other/file', 0700) 

This has the advantage that you can put full statements, and more than one of them, in each common_handling block.

Keep in mind though, your need to use the same handling over and over again feels a lot like over-handling exceptions. Are you sure you need to do this much?

like image 61
Ned Batchelder Avatar answered Oct 20 '22 04:10

Ned Batchelder