Bird
Raised Fist0
Pythonprogramming~20 mins

Automatic resource cleanup in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Automatic Resource Cleanup Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code using a context manager?
Consider the following Python code that uses a context manager to open a file and write text. What will be printed when this code runs?
Python
with open('testfile.txt', 'w') as f:
    f.write('Hello world')
print(f.closed)
Atrue
Bfalse
CRaises a NameError
Dnull
Attempts:
2 left
💡 Hint
Think about what the context manager does after the block finishes.
Predict Output
intermediate
2:00remaining
What happens if an exception occurs inside a 'with' block?
What will be the output of this code snippet?
Python
class Resource:
    def __enter__(self):
        print('Resource acquired')
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Resource released')
        return false

try:
    with Resource() as r:
        print('Inside with block')
        raise ValueError('Oops')
except ValueError:
    print('Exception caught')
AResource acquired\nInside with block\nResource released\nException caught
BResource acquired\nResource released\nInside with block\nException caught
CResource acquired\nInside with block\nException caught
DInside with block\nResource acquired\nResource released\nException caught
Attempts:
2 left
💡 Hint
The __exit__ method runs even if an exception happens inside the block.
🔧 Debug
advanced
2:00remaining
Why does this custom context manager fail to release the resource?
This code tries to create a context manager but the resource is not released after the block. What is the bug?
Python
class MyResource:
    def __enter__(self):
        print('Acquiring resource')
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Releasing resource')

with MyResource() as r:
    print('Using resource')
AThe __exit__ method is missing a return statement, so the resource is not released.
BThe __exit__ method should return true to suppress exceptions, but it doesn't.
CThe __exit__ method is defined but does not handle exceptions properly, causing resource leak.
DThe __exit__ method is missing the 'self' parameter, so it is not called.
Attempts:
2 left
💡 Hint
Returning true from __exit__ suppresses exceptions, but not returning anything returns null.
📝 Syntax
advanced
2:00remaining
Which option correctly implements a context manager using 'contextlib'?
Select the code snippet that correctly creates a context manager using the @contextmanager decorator from contextlib.
A
from contextlib import contextmanager

@contextmanager
def managed():
    print('Start')
    return
    print('End')
B
from contextlib import contextmanager

def managed():
    print('Start')
    yield
    print('End')
C
from contextlib import contextmanager

@contextmanager
def managed():
    print('Start')
    yield
    print('End')
D
from contextlib import contextmanager

@contextmanager
def managed():
    print('Start')
    yield 1
    print('End')
    yield 2
Attempts:
2 left
💡 Hint
The function must be decorated and use exactly one yield to separate setup and cleanup.
🚀 Application
expert
2:00remaining
How many times is the resource released in this nested context manager code?
Analyze the following code and determine how many times 'Resource released' is printed.
Python
class Resource:
    def __enter__(self):
        print('Resource acquired')
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Resource released')

with Resource() as r1:
    with Resource() as r2:
        print('Inside nested with')
A1
B0
C3
D2
Attempts:
2 left
💡 Hint
Each 'with' block calls __enter__ and __exit__ once.

Practice

(1/5)
1. What is the main purpose of using the with statement in Python for resource management?
easy
A. To create infinite loops easily
B. To automatically release resources like files or locks after use
C. To define functions inside other functions
D. To import modules dynamically

Solution

  1. Step 1: Understand resource management

    The with statement is designed to handle resources such as files or locks safely.
  2. Step 2: Identify automatic cleanup

    It ensures resources are released automatically after the block finishes, preventing leaks.
  3. Final Answer:

    To automatically release resources like files or locks after use -> Option B
  4. Quick Check:

    Automatic cleanup = To automatically release resources like files or locks after use [OK]
Hint: Think: with = automatic resource release [OK]
Common Mistakes:
  • Confusing with loops or function definitions
  • Thinking it imports modules
  • Assuming manual cleanup is still needed
2. Which of the following is the correct syntax to open a file for reading using automatic resource cleanup?
easy
A. open with('file.txt', 'r') as f:
B. with open('file.txt', 'r') f:
C. with open('file.txt', 'r') as f:
D. open('file.txt', 'r') with as f:

Solution

  1. Step 1: Recall correct with syntax

    The correct syntax starts with with, followed by the resource expression, then as and a variable.
  2. Step 2: Match syntax to options

    with open('file.txt', 'r') as f: matches the correct pattern: with open('file.txt', 'r') as f:
  3. Final Answer:

    with open('file.txt', 'r') as f: -> Option C
  4. Quick Check:

    Correct with syntax = with open('file.txt', 'r') as f: [OK]
Hint: Remember: with + resource + as + variable [OK]
Common Mistakes:
  • Misplacing 'with' keyword
  • Omitting 'as' keyword
  • Wrong order of keywords
3. What will be the output of this code?
with open('test.txt', 'w') as f:
    f.write('Hello')
print(f.closed)
medium
A. Error: f is not defined
B. False
C. Hello
D. True

Solution

  1. Step 1: Understand the with block effect

    The file is opened and written inside the with block, which automatically closes the file after the block ends.
  2. Step 2: Check the f.closed property after block

    After the block, the variable f is out of scope and not defined, so accessing f.closed raises a NameError.
  3. Final Answer:

    Error: f is not defined -> Option A
  4. Quick Check:

    Variable f is local to with block, so f.closed access outside causes error [OK]
Hint: f is only defined inside with block; outside it is undefined [OK]
Common Mistakes:
  • Thinking file stays open after with block
  • Expecting file content as output
  • Assuming f is defined outside with
4. Identify the error in this code snippet:
with open('data.txt', 'r') as file:
    content = file.read()
file.close()
medium
A. No error, code is correct
B. Missing colon after with statement
C. Indentation error on content assignment
D. Calling file.close() is unnecessary and causes an error

Solution

  1. Step 1: Understand automatic closing with with

    The with statement automatically closes the file after the block ends.
  2. Step 2: Check explicit close call

    Calling file.close() outside the block is unnecessary, but Python file objects handle multiple calls to close() gracefully without raising an error.
  3. Final Answer:

    No error, code is correct -> Option A
  4. Quick Check:

    Explicit close after with = no error [OK]
Hint: with handles closing; extra close() is harmless [OK]
Common Mistakes:
  • Believing file.close() causes an error after with
  • Looking for syntax errors like missing colon
  • Suspecting indentation problems
5. You want to safely acquire and release a lock using automatic resource cleanup. Which code snippet correctly uses with for this purpose?
import threading
lock = threading.Lock()

# Choose the correct usage
A) with lock.acquire():
       print('Lock acquired')
B) with lock.acquire:
       print('Lock acquired')
C) with lock:
       print('Lock acquired')
D) with lock.lock():
       print('Lock acquired')
hard
A. with lock.acquire():
B. with lock.acquire:
C. with lock.lock():
D. with lock:

Solution

  1. Step 1: Understand lock context management

    Python's threading.Lock supports the context manager protocol, so you can use with lock: to acquire and release automatically.
  2. Step 2: Analyze options

    with lock: uses with lock:, which is correct. Other options misuse the acquire method or call non-existent methods.
  3. Final Answer:

    with lock: -> Option D
  4. Quick Check:

    Use lock directly in with = with lock: [OK]
Hint: Use 'with lock:' to auto acquire and release locks [OK]
Common Mistakes:
  • Calling lock.acquire() inside with
  • Using wrong method names
  • Not knowing Lock supports context manager