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.

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Just the example I'm looking for. And also I spot an error in my post.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.