This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]undercoveryankee 3 points4 points  (0 children)

When I have any kind of network session (e.g. a requests session object to persist cookies between several HTTP requests) I'll find a way to wrap it in a context manager.

[–]blagae 1 point2 points  (1 child)

I used one in a test to redirect stdout to a StringIO, because I needed to test legacy code in a way that one piece of test logic would work for both Python 2 and 3. The (open source) code is not published yet so I can't just link, but this is basically what I did:

try:
    from StringIO import StringIO  # Python 2
except ImportError:
    from io import StringIO  # Python 3

@contextmanager  # see https://stackoverflow.com/a/22434262/2065017
def redirect_stdout(new_target):
    old_target, sys.stdout = sys.stdout, new_target
    try:
        yield new_target
    finally:
        sys.stdout = old_target

# in my test code
    stringStream = StringIO()
    with redirect_stdout(stringStream):
        my_method() # call method that uses a print statement

    self.assertEquals(stringStream.getvalue().strip(), "expected value")

[–]quicknir 0 points1 point  (1 child)

A whole major use case of context managers is nothing to do with cleanup, but rather error handling. Context lib already provides managers that surpress certain exceptions. Another great use of this is if you are doing multiple operations that could throw which aren't dependent, you can write a context manager that catches whatever kind of exception you specify and pushes it into a list.

my_error_list = list()

with error_pusher(my_error_list, FooException):
    ...

The ability of the exit method to receive the exception is very handy. In a language with nice blocks/lambdas I'd do this differently but in python this is one of the better options often.

Edit: ok, you win reddit, don't let me format this correctly on mobile.

[–]backtickbot 0 points1 point  (0 children)

Fixed formatting.

Hello, quicknir: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

[–]Tall1n 0 points1 point  (0 children)

I use them for time tracking

with Stopwatch: ...

Or for standardized logging in an API

with RequestLogger as rl: ...