3

I was reading this question and it comes to my mind I needed it also, but in Python. So I'm wondering if there is a way of doing that with the with statement in Python.

Basically what I want is some kind of IDisposable (C#) analogy in Python. I know, for sure it will be a little different, I think something like:

class ForUseInWith(IDisposableLike):
    #something here
    pass

and use it like this:

with ForUseInWith() as disposable:
    #something here
    pass

Currently I'm figuring out how to do this studying the python reference and the PEP 343, if I manage to do a good solution and a clever example I will post here the answer. But in the way maybe you can help me.

Community
  • 1
  • 1
Alvaro Fuentes
  • 16,937
  • 4
  • 56
  • 68

1 Answers1

6

It is easy to do, you just need to have an __enter__ and an __exit__ method in your class.

Example:

class ForUseInWith(object):

    def test(self):
        print 'works!'

    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        pass

Using It:

>>> with ForUseInWith() as disposable:
    disposable.test()

works!

Expanding It:

You can of course, have an __init__ method which receives parameters (like open() does) and you can also include ways of handling errors/exceptions in the __exit__ method. This kind of structure is best used for simple classes which also have a requirement to be able to be disposed, or be one-off processes that don't need to stick around or have complicated disposal

Inbar Rose
  • 41,843
  • 24
  • 85
  • 131