Python isinstance
Inspect an imported object's type before formatting its integer fare.
A simple example
isinstance
- Start with Text "2" where an integer is required
- Do this Check or cast the type
- Result Type mismatch
Syntax
isinstance(fare, int)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyCheck the type of an imported fare
A transit app imports fares from two ticket machines. One machine sends the word “free” in a field normally filled with a whole number, so the importer needs to flag the record for review.
fare = "free"
if isinstance(fare, int) and not isinstance(fare, bool):
print(fare)
else:
print("Review fare type")
Review fare type
The imported value holds text. The desk flags the fare before treating it as a number.
Import a museum headcount
The counter sends the number 36 as an integer object. The import expects an integer value. Flag a text field for review before calculating a total.
Review a quoted fare
A new terminal sends its fare as text in a field that previously carried an integer. The import expects an integer value. Flag a text field for review before calculating a total.
What to watch for
In Python, bool is a subclass of int. A fare field should explicitly reject booleans.