How to use the ValueError ExceptionType in Python for Function Input Validation
1 min readSep 1, 2022
The aim of this page📝 is to add a small usecase for ValueError
Exception type in python. For example
def validate_and_capitalize(section_name: str, section_folders: list) -> str:
if not re.match(r"\d\d\s.*", section_name):
raise ValueError(f"The first 2 characters need to be a sectionID, e.g. 66")
# ...
- The idiomatic use is to start function with input validation
- Raise handled exception with
ValueError
and description of what is wrong - Typical methods are
isalpha()
,isdigit()
,in
operator andlen()
of the input - Given a string representing one Unicode character, return an integer representing the Unicode cod
- This is from a lesson I am currently taking
def create(owner_code, serial, category='U'):
"""Create an ISO 6346 shipping container code.
Args:
owner_code (str): Three character alphabetic container code.
serial (str): Six digit numeric serial number.
category (str): Equipment category identifier.
Returns:
An ISO 6346 container code including a check digit.
Raises:
ValueError: If incorrect values are provided.
"""
if not (len(owner_code) == 3 and owner_code.isalpha()):
raise ValueError("Invalid ISO 6346 owner code '{}'".format(owner_code))
if category not in ('U', 'J', 'Z', 'R'):
raise ValueError("Invalid ISO 6346 category identifier '{}'".format(category))
if not (len(serial) == 6 and serial.isdigit()):
raise ValueError("Invalid ISO 6346 serial number")
# ...