views:

54

answers:

2

Hi , I am new to this and am just trying to understand the with statement.I get to understand that it is supposed to replace the try except block.Now suppose I do something like this:-

try:
   name='rubicon'/2 #to raise an exception
except Exception,e:
   print "no not possible"
finally:
   print"Ok I caught you"

Now how do I replace it with a context manager.

(well yes it is a totally amateurish, but please bear with me :-) )

+2  A: 

with doesn't really replace try/except, but, rather, try/finally. Still, you can make a context manager do something different in exception cases from non-exception ones:

class Mgr(object):
    def __enter__(self): pass
    def __exit__(self, ext, exv, trb):
        if ext is not None: print "no not possible"
        print "OK I caught you"
        return True

with Mgr():
    name='rubicon'/2 #to raise an exception

The return True part is where the context manager decides to suppress the exception (as you do by not re-raising it in your except clause).

Alex Martelli
thanks a lot.. that was very clear!
@rubicon, you're welcome! When you've received enough answers and tried them out, if one has helped you, be sure to accept it (by clicking the checkmark-shaped icon next to the answer) -- that's fundamental SO etiquette!-)
Alex Martelli
Oh sorry ! done thanks again!
+1  A: 

The with in Python is intended for wrapping a set of statements where you should set up and destroy or close resources. It is in a way similar to try...finally in that regard as the finally clause will be executed even after an exception.

A context manager is an object that implements two methods: __enter__ and __exit__. Those are called immediately before and after (respectively) the with block.

For instance, take a look at the classic open() example:

with open('temp.txt', 'w') as f:
    f.write("Hi!")

Open returns a File object that implements __enter__ more or less like return self and __exit__ like self.close().

Pablo Alejandro Costesich