Conditions and Cleanup
Lesson 28 of 48 in Coddy's Python for R Developers course.
R has separate error and warning conditions, handled with tools such as tryCatch and withCallingHandlers. Python uses exception classes for failures; int on malformed text raises ValueError rather than producing NA with a warning. R on.exit schedules cleanup when a function exits. Python finally or with can ensure cleanup when protected work finishes, including exceptional exits. A context manager's exit method can suppress an exception only when it returns a truthy value. Catch the specific failure the parser expects and leave unrelated programming errors visible. Range checks are separate from successful numeric conversion.
R
work <- function() {
on.exit(cat("released\n"))
stop("bad data")
}
tryCatch(work(), error=function(e) cat("invalid\n"))Python
class Managed:
def __enter__(self):
return self
def __exit__(self, kind, value, trace):
print('released')
return False
try:
with Managed():
int('oops')
except ValueError:
print('invalid')Porting trap
Suppressing R warnings is not a substitute for checking a conversion result. Python parsing requires explicit exception handling instead.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler