Harness the Python “With” Statement

Arg. I love the python “with” statement, but I can never remember the signatures of the methods to support it. So here it is:

class with_class():
    def __enter__(self):
        return self  # or something else

    def __exit__(self, type, value, traceback):
        pass

with with_class() as thing:
    pass

Taken from this awesome page, which explains it really well:

http://effbot.org/zone/python-with-statement.htm

Advertisements

Leave a comment

Filed under python, Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s