Python 3D Academyবাংলা

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:

  1. isinstance(value, int) asks "is this value an int?" and gives back True or False
  2. a tuple asks about several types at once: isinstance(x, (int, float))
  3. if the check fails, stop with a clear TypeError that says what was expected and what came
  4. 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)
Without the guard, 500 + "250" would still fail, but with a confusing message. The guard says exactly what went wrong.

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)
zip pairs each label (name, kind) with the argument in the same place. The second call stops at the gate.

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 for bool first if it must be refused (above).
  • type(x) == int. It refuses subclasses and reads worse; isinstance is the usual way.
  • Checking against a parameterized hint. isinstance(x, list[int]) is a TypeError; check list, then the items if needed.
  • The wrong error. A wrong type is a TypeError; a right type with a bad value is a ValueError.

Quiz

  1. What does this print?

    print(isinstance(5, int), isinstance("5", int))
  2. What does this print?

    print(isinstance(True, int))
  3. Which error fits best when a value has the wrong type?

    • TypeError
    • ValueError
    • KeyError
  4. 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)
  5. What does this print?

    for x in [3, 2.5, "7"]:
        print(isinstance(x, (int, float)))
  6. 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

  1. Add a guard to safe_double(n: int) -> int: if n isn't an int, raise TypeError; otherwise give back n * 2.

  2. Write total_price(prices: list[int]) -> int: the sum of the prices, but raise TypeError if 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.)

  3. Finish the decorator checked: before calling func, it checks each positional argument against func's labels in __annotations__ (in order, skipping "return") and raises TypeError("<name> must be <type>"), like "times must be int". Keep the function's name with functools.wraps. (message is written for you.)