Bird
Raised Fist0
Pythonprogramming~20 mins

Best practices for resource management 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
🎖️
Resource Management Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of using context manager with file handling
What is the output of this Python code snippet?
Python
with open('test.txt', 'w') as f:
    f.write('Hello')
print(f.closed)
ATrue
BFalse
CRaises a NameError
DNone
Attempts:
2 left
💡 Hint
Think about what happens to the file after the with block ends.
🧠 Conceptual
intermediate
2:00remaining
Why use 'with' statement for resource management?
Which of the following best explains why using the 'with' statement is recommended for resource management in Python?
AIt automatically handles opening and closing resources, even if errors occur.
BIt makes the code run faster by caching resources.
CIt allows resources to stay open indefinitely for reuse.
DIt disables error messages related to resource usage.
Attempts:
2 left
💡 Hint
Think about what happens if an error occurs inside a 'with' block.
🔧 Debug
advanced
2:00remaining
Identify the resource leak in this code
What is the main problem with this code snippet regarding resource management?
Python
def read_file(filename):
    f = open(filename, 'r')
    data = f.read()
    return data

content = read_file('data.txt')
AThe file is opened in write mode instead of read mode.
BThe file is closed too early before reading.
CThe file is never closed, causing a resource leak.
DThe function returns None instead of file content.
Attempts:
2 left
💡 Hint
Think about what happens to the file after reading.
📝 Syntax
advanced
2:00remaining
Correct syntax for custom context manager
Which option correctly defines a custom context manager class in Python?
Python
class MyResource:
    def __enter__(self):
        print('Resource acquired')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Resource released')
A
class MyResource:
    def enter(self):
        return self
    def exit(self, exc_type, exc_val, exc_tb):
        pass
B
class MyResource:
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        pass
C
class MyResource:
    def __enter__(self):
        return self
    def __exit__(self):
        pass
D
class MyResource:
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val):
        pass
Attempts:
2 left
💡 Hint
Check the method names and parameters required for context managers.
🚀 Application
expert
3:00remaining
Using contextlib to manage resources
Which option correctly uses the contextlib module to create a context manager that prints messages on enter and exit?
Python
from contextlib import contextmanager

@contextmanager
def managed_resource():
    print('Start')
    yield
    print('End')
A
with managed_resource():
    print('Inside')

# Output:
# Start
# End
# Inside
B
with managed_resource:
    print('Inside')

# Output:
# Start
# Inside
# End
C
with managed_resource():
    print('Inside')

# Output:
# Inside
# Start
# End
D
with managed_resource():
    print('Inside')

# Output:
# Start
# Inside
# End
Attempts:
2 left
💡 Hint
Remember to call the function to get the context manager object.

Practice

(1/5)
1.

Why is it recommended to use the with statement when working with files in Python?

easy
A. It automatically closes the file after the block ends.
B. It makes the file open faster.
C. It prevents the file from being read.
D. It duplicates the file content.

Solution

  1. Step 1: Understand the with statement role

    The with statement ensures that resources like files are properly closed after use, even if errors occur.
  2. Step 2: Recognize automatic resource management

    Using with automatically calls the file's close() method when the block finishes.
  3. Final Answer:

    It automatically closes the file after the block ends. -> Option A
  4. Quick Check:

    with closes files automatically [OK]
Hint: Remember: with auto-closes resources [OK]
Common Mistakes:
  • Thinking with speeds up file opening
  • Believing with prevents reading
  • Assuming with duplicates content
2.

Which of the following is the correct syntax to open a file named data.txt for reading using with?

?
easy
A. open with('data.txt', 'r') as file:
B. with open('data.txt') file:
C. with open('data.txt', 'r') as file:
D. with open('data.txt', 'read') as file:

Solution

  1. Step 1: Recall correct open syntax

    The correct way to open a file for reading is open(filename, 'r').
  2. Step 2: Check with statement syntax

    The with statement requires with open(...) as variable: format.
  3. Final Answer:

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

    Correct with open syntax = with open('data.txt', 'r') as file: [OK]
Hint: Use with open(filename, 'r') as var: [OK]
Common Mistakes:
  • Omitting 'as' keyword
  • Using 'read' instead of 'r' mode
  • 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. True
B. False
C. Hello
D. Error

Solution

  1. Step 1: Understand with block effect on file

    The with block opens the file and closes it automatically after the block ends.
  2. Step 2: Check f.closed after block

    Since the file is closed after the block, f.closed will be True.
  3. Final Answer:

    True -> Option A
  4. Quick Check:

    File closed after with block = True [OK]
Hint: File is closed after with block ends [OK]
Common Mistakes:
  • Thinking file stays open after with
  • Expecting file content printed
  • Confusing f.closed value
4.

Find the error in this code snippet:

file = open('log.txt', 'w')
file.write('Start logging')
# forgot to close the file
medium
A. File is not opened in read mode.
B. File name should be a variable.
C. File write syntax is incorrect.
D. File is not closed after writing.

Solution

  1. Step 1: Check file opening and writing

    The file is opened correctly in write mode and data is written properly.
  2. Step 2: Identify missing resource management

    The file is not closed after writing, which can cause data loss or resource leaks.
  3. Final Answer:

    File is not closed after writing. -> Option D
  4. Quick Check:

    Always close files after use [OK]
Hint: Always close files or use with [OK]
Common Mistakes:
  • Ignoring missing close() call
  • Thinking write syntax is wrong
  • Confusing file modes
5.

You want to read multiple files and combine their contents safely. Which approach is best?

?
hard
A. Open all files without with and close manually later.
B. Use nested with statements to open each file safely.
C. Open files with open() but never close them.
D. Read files using open() without closing or with.

Solution

  1. Step 1: Consider resource safety when reading multiple files

    Opening multiple files requires careful closing to avoid leaks or errors.
  2. Step 2: Use nested with statements

    Nested with ensures each file is opened and closed properly, even if errors occur.
  3. Final Answer:

    Use nested with statements to open each file safely. -> Option B
  4. Quick Check:

    Nested with = safe multi-file handling [OK]
Hint: Use nested with for multiple files [OK]
Common Mistakes:
  • Not closing files manually
  • Opening many files without with
  • Ignoring errors during file operations