Exceptions and RAII
Lesson 28 of 48 in Coddy's Python for C++ Developers course.
C++ automatic objects run destructors on ordinary scope exit and during exception unwinding: RAII ties resource lifetime to object lifetime. Python collection timing is not a portable cleanup contract, and __del__ is not a direct RAII replacement. Use with for deterministic release through a context manager. Its __exit__ runs when the suite exits, including on an exception. Catch specific exceptions with except, and raise ValueError for invalid domain input. Validate before changing state.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
struct Guard {
~Guard() { std::cout << "released\n"; }
};
try {
Guard guard;
throw std::invalid_argument("bad");
} catch (const std::invalid_argument&) {
std::cout << "invalid\n";
}Python
class Guard:
def __enter__(self):
return self
def __exit__(self, kind, value, trace):
print("released")
try:
with Guard():
int("bad")
except ValueError:
print("invalid")Porting trap
A with block does not introduce C++ block scope. The bound name may remain afterward, but a resource such as a file can already be closed. A context manager may suppress an exception if __exit__ returns a truthy value; the example returns None, so the exception reaches except.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
Challenge
BeginnerImplement parse_capacity(text). Convert the string with int. Accept integers from 0 through 500, inclusive, and return the integer. Raise ValueError for malformed text or out-of-range values. Do not print or read input. The driver reads one line, prints the returned capacity, or prints invalid when ValueError is raised. Surrounding whitespace and a leading plus sign are allowed by integer conversion.
The locked driver also calls your function with invalid arguments to verify the required exceptions. A successful result must be an integer; returning error text does not satisfy the contract. These checks produce no additional output.
Your function definitions go in functions.py. The locked driver.py imports them and handles the supplied input/output and checks. You do not need to edit the driver.
Try it yourself
from functions import parse_capacity
_coddy_line = input()
try:
_coddy_result = parse_capacity(_coddy_line)
except ValueError:
print("invalid")
else:
if type(_coddy_result) is not int:
raise AssertionError("parse_capacity must return an integer on success")
print(_coddy_result)
for _coddy_invalid in ("oops", "-1", "501"):
try:
parse_capacity(_coddy_invalid)
except ValueError:
pass
else:
raise AssertionError("parse_capacity must raise ValueError for invalid input")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler