1

I have many blocks of code like this:

try:
  a = get_a()
  try:
    b = get_b()

    # varying codes here, where a and b are used

  finally:
    if b:
      cleanup(b)
finally:
  if a:
    cleanup(a)

I hope to write some magic code like this:

some_magic:
  # varying codes here, where a and b are also available

Is this possible?

1
  • Why not merge them both inside a single try and finally? Commented Mar 9, 2016 at 10:06

2 Answers 2

5

If you can't or don't want to implement context protocol for a and b, you can use contextlib facilities to make a context:

from contextlib import contextmanager

@contextmanager
def managed(a):
    try:
        yield a
    finally:
        if a:
            cleanup(a)

with managed(get_a()) as a, managed(get_b()) as b:
    # do something here
    pass
Sign up to request clarification or add additional context in comments.

1 Comment

upvoted (was about to write that after hunting references)
3

Let classes of a and b implement the context manager protocol, and use the with statement:

with get_a() as a, get_b() as b:
    do_magic

Now if get_a and get_b returned open file handles, they'd be automatically closed at the end of the block. If the values returned are of a custom class, that class should have the __enter__ and __exit__ magic methods.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.