pcall to Exceptions
Lesson 28 of 48 in Coddy's Python for Lua Developers course.
Lua pcall returns a success flag followed by results or an error object. Python uses try and except to handle raised exceptions by type. int on invalid text raises ValueError; Lua tonumber instead returns nil unless you turn that failure into an error. Catch only the failure you can recover from. Python with uses a context manager for cleanup when a block exits, including by exception. Avoid relying on garbage collection for timely resource release.
Lua example
local ok = pcall(function()
local n = tonumber("bad")
if n == nil then error("invalid number") end
end)
if not ok then print("invalid") endPython
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 Python context manager can suppress an exception by returning a truthy exit result. The displayed manager does not suppress, so the handler runs after cleanup.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
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 Lua Developers
1From Lua to Python
Run Your First Python ProgramPrinting and TextNames and Local ScopeNumbers and ConversionSuites Instead of endRecap: Rewrite a Receipt4Iteration and Transformations
Numeric for to rangepairs, ipairs, and itemsLoop Control and SkipsComprehensions and SortingRecap: Build a Ranking2Values and Decisions
nil Versus NoneTable Identity and EqualityTruthiness Is Differentelif and Value SelectionRecap: Eligibility Rules3Tables to Typed Collections
Sequence Tables to ListsTuples and Multiple ReturnsRecords to DictionariesSets and Shared TablesRecap: Clean an Inventory6Errors and Modules
Input and Exact Textpcall to Exceptionsrequire to importHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler