Checking types yourself with isinstance
🌍 In real life. A concert poster says ticket required. The poster doesn't stop anyone; the guard at the gate does, by looking at each ticket as people walk in.
Type hints are the poster. When a wrong type would cause real damage (a price saved as text, a bank balance that's a list), you can put a guard at the top of your function. Step by step:
isinstance(value, int)asks "is this value an int?" and gives backTrueorFalse- a tuple asks about several types at once:
isinstance(x, (int, float)) - if the check fails, stop with a clear
TypeErrorthat says what was expected and what came - only then do the real work
The idea in one sentence: when a wrong type would do real damage, check it yourself with isinstance and raise a TypeError, since the hints alone won't stop anything.
Its words:
- guard: a check at the start of a function that refuses a bad value
isinstance(x, (int, float)): a tuple of types means "any of these"__annotations__: a dictionary of a function's hints, which a decorator can read
def add_to_balance(balance: int, amount: int) -> int:
if not isinstance(amount, int):
raise TypeError(f"amount must be an int, got {type(amount).__name__}")
return balance + amount
print(add_to_balance(500, 250))
try:
add_to_balance(500, "250")
except TypeError as e:
print("refused:", e)A surprise: True is an int. In Python, bool is a kind of int (True behaves like 1 and False like 0), so isinstance(True, int) is True. If a bool must not count as a number, check for it first:
for value in [5, 2.5, "5", True]:
print(repr(value), isinstance(value, int), isinstance(value, (int, float)))
def is_count(value) -> bool:
return isinstance(value, int) and not isinstance(value, bool)
print(is_count(5), is_count(True))A guard for every label: reading __annotations__. Writing the same check in every function gets tiring. With a decorator (Chapter 27) you can write the guard once: it reads the function's own labels from __annotations__ and checks each argument against them.
This works for plain types like int and str. isinstance can't check inside a list[int], so a real project would use a library (or a type checker) for those.
import functools
def checked(func):
hints = {k: v for k, v in func.__annotations__.items() if k != "return"}
@functools.wraps(func)
def wrapper(*args):
for (name, kind), value in zip(hints.items(), args):
if not isinstance(value, kind):
raise TypeError(f"{name} must be {kind.__name__}, got {type(value).__name__}")
return func(*args)
return wrapper
@checked
def ticket(name: str, seat: int) -> str:
return f"{name}: seat {seat}"
print(ticket("Mina", 12))
try:
print(ticket("Rafi", "12"))
except TypeError as e:
print("guard:", e)Why not check everything? Checks cost a little time and a lot of reading. Put guards where bad data enters (user input, files, other people's code), and trust the hints and tests inside your own program.
Mistakes and edge cases.
- True passing as a number.
isinstance(True, int)is True; check forboolfirst if it must be refused (above). - type(x) == int. It refuses subclasses and reads worse;
isinstanceis the usual way. - Checking against a parameterized hint.
isinstance(x, list[int])is a TypeError; checklist, then the items if needed. - The wrong error. A wrong type is a
TypeError; a right type with a bad value is aValueError.
Quiz
What does this print?
print(isinstance(5, int), isinstance("5", int))What does this print?
print(isinstance(True, int))Which error fits best when a value has the wrong type?
- TypeError
- ValueError
- KeyError
What does this print?
def double(n: int) -> int: if not isinstance(n, int): raise TypeError("n must be an int") return n * 2 try: print(double(4)) print(double("ab")) except TypeError as e: print(e)What does this print?
for x in [3, 2.5, "7"]: print(isinstance(x, (int, float)))This guard should refuse True as an age, but it lets it through. Which line is the problem?
def set_age(age): if not isinstance(age, int): raise TypeError("age must be a whole number") return age print(set_age(True))
Coding tasks
Add a guard to
safe_double(n: int) -> int: ifnisn't an int, raiseTypeError; otherwise give backn * 2.Write
total_price(prices: list[int]) -> int: the sum of the prices, but raiseTypeErrorif any price isn't a whole number. A bool isn't a price either. (Paise are kept as whole numbers, so 2.5 is refused.)Finish the decorator
checked: before callingfunc, it checks each positional argument againstfunc's labels in__annotations__(in order, skipping"return") and raisesTypeError("<name> must be <type>"), like"times must be int". Keep the function's name withfunctools.wraps. (messageis written for you.)