Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python warnings code

Practice issuing caller-attributed deprecation warnings, defining a warning category, escalating selected warnings, and capturing warnings in a test.

Intermediate ~9 min read

Challenge 1

Warn callers that the API is deprecated, and attribute the warning to the call site.

python Your answer
import warnings

def old_api():
    

with warnings.catch_warnings(record=True) as recorded:
    warnings.simplefilter("always")
    old_api()
print(recorded[0].category.__name__)

Press Ctrl⌘Enter to check your answer

Challenge 2

Ensure the test captures every matching warning, including repeated calls.

python Your answer
import warnings

with warnings.catch_warnings(record=True) as recorded:
    
    warnings.warn("A value was normalized", UserWarning)
print(len(recorded))

Press Ctrl⌘Enter to check your answer

Challenge 3

Use the custom category for the warning that is about to be issued.

python Your answer
import warnings

class DataFormatWarning(UserWarning):
    pass

with warnings.catch_warnings(record=True) as recorded:
    warnings.simplefilter("always")
    warnings.warn("A field was omitted", )
print(recorded[0].category.__name__)

Press Ctrl⌘Enter to check your answer

Challenge 4

Make UserWarning instances raise exceptions inside this scoped warning context.

python Your answer
import warnings

with warnings.catch_warnings():
    
    try:
        warnings.warn("An option will be ignored", UserWarning)
    except UserWarning:
        print("warning treated as error")

Press Ctrl⌘Enter to check your answer