Sub topic 3
Dynamic typing and checking types with type()
This chapter assumes you can run Python code and use print(). It also assumes you know what a name and an assignment are, as covered in the previous chapters. Here you will learn where Python keeps type information, how to inspect it, and how to avoid the mistakes that come from assuming a name has a fixed type.
Types belong to objects, not names
In languages such as C or Java, you declare a variable with a type, and the variable can hold only that type. Python works differently. Every object carries its own type. A name is only a label bound to an object, and it has no type of its own.
This is called dynamic typing. The type is checked when the code runs, not before. You can bind the same name to an int and later to a string.
count = 3
price = 4.5
name = "Ada"
print(type(count), type(price), type(name))
count = "three"
print(type(count))The first line prints <class 'int'> <class 'float'> <class 'str'>. The last line prints <class 'str'>, because count now refers to a different object. Nothing was converted. The name moved from one object to another.
What type() returns
type(obj) returns the class of the object. The result is itself an object, so you can compare it, store it, or print it.
print(type(3) is int)
print(type(3.0))
print(type(None))
print(type([1, 2]))
print(type(int))This prints True, <class 'float'>, <class 'NoneType'>, <class 'list'>, and <class 'type'>. The last result shows that classes are objects too, and their type is type.
Some common literals and their types:
| Expression | Type reported |
|---|---|
| `42` | `int` |
| `3.14` | `float` |
| `"text"` | `str` |
| `True` | `bool` |
| `None` | `NoneType` |
| `b"raw"` | `bytes` |
Reading the output
The output <class 'int'> is the printed form of the class object. If you want only the name as a string, use type(x).__name__. That is useful in error messages and logs.
value = 2.5
print(type(value).__name__)
print(f"Got {type(value).__name__}, expected int")This prints float and then Got float, expected int.
Strong typing at runtime
Dynamic typing does not mean Python converts types freely. Python is dynamically typed but also strongly typed. It will not guess how to combine a string and an integer. It raises an error when the operation runs.
def add_one(value):
return value + 1
print(add_one(2))
print(add_one(2.5))
try:
print(add_one("2"))
except TypeError as e:
print("TypeError:", e)The output is 3, then 3.5, then TypeError: can only concatenate str (not "int") to str. The function has no declared parameter type, so the call with "2" is accepted by the language. The failure happens only when + is evaluated.
Mixed numeric types are an exception that Python does define. Adding an int to a float gives a float, because Python has an explicit rule for numbers.
Where errors appear
Because checks happen at run time, a type mistake in a rarely used branch can stay hidden until that branch executes. Tests that cover each branch are how you catch these problems. Static checkers such as mypy or pyright can also catch them before the program runs, using annotations.
Annotations are hints, not enforcement
You can annotate names and parameters with types. Python stores these hints but does not enforce them.
def double(n: int) -> int:
return n * 2
print(double(4))
print(double("ab"))This prints 8 and then abab. The second call breaks the declared contract, but Python runs it anyway, because * works on a string and an integer. Annotations help readers and external tools. They do not change how the program runs.
Checking types: type() versus isinstance()
There are two ways to ask what an object is. They answer different questions.
type(x) is Tasks whether the exact class ofxisT.isinstance(x, T)asks whetherxis an instance ofTor of any subclass ofT. It also accepts a tuple of types.
The difference matters with bool. The class bool is a subclass of int, so True counts as an integer for isinstance.
flag = True
print(type(flag) is int)
print(type(flag) is bool)
print(isinstance(flag, int))
print(isinstance(flag, (int, float)))
print(isinstance(3.0, int))The output is False, True, True, True, False. Note the last line. The value 3.0 is a float, even though it equals the integer 3. The type depends on how the object was made, not on its value.
Use isinstance() for almost all type checks in real code. It respects subclassing, which is what callers usually expect. Use type(x) is T only when you must exclude subclasses. For example, you might want to treat bool separately from int.
Duck typing and when to check
Python code often avoids type checks entirely. If an object supports the operations you use, it works. This style is called duck typing: if it behaves like the type you need, treat it as that type.
def total_length(items):
return sum(len(item) for item in items)
print(total_length(["ab", "cde"]))
print(total_length([[1, 2], (3, 4, 5)]))This prints 5 and then 5. The function never asks for strings. Anything with a length works, including lists and tuples.
Check types explicitly in a few situations:
- At a trust boundary, such as data read from a file, a network request, or user input. These values are often strings even when they look like numbers.
- When behavior must differ by type, and no common operation covers both cases.
- When a clear error message early is better than a confusing failure later.
def parse_quantity(raw):
if isinstance(raw, bool):
raise TypeError("quantity cannot be a bool")
if isinstance(raw, int):
return raw
if isinstance(raw, str):
return int(raw)
raise TypeError(f"unsupported type: {type(raw).__name__}")
print(parse_quantity(5))
print(parse_quantity("12"))
try:
parse_quantity(2.5)
except TypeError as e:
print("TypeError:", e)The output is 5, 12, and TypeError: unsupported type: float. The bool check comes first on purpose. Because bool is a subclass of int, the integer branch would otherwise accept True as the quantity 1.
Common mistakes
- Assuming a name keeps its type. A name can be rebound at any point, so a function that receives a parameter has no guarantee about its type unless you check it or rely on tests.
- Reusing one name for different meanings. Rebinding
countfrom a number to a string, as in the first example, is legal but makes code hard to read. Choose a new name when the meaning changes. - Confusing value with type. The values
3and3.0are equal under==, but their types differ. The check3 == 3.0isTrue, andtype(3) is type(3.0)isFalse. - Treating input as numbers. The result of
input()is always astr. Convert it explicitly, as later chapters show. - Trusting annotations. A hint like
n: intdoes not stop a caller from passing a string.
Summary of the working model
Objects have types. Names do not. type() reports the class of the object a name currently refers to. Python checks types when an operation runs, and it raises TypeError instead of guessing. Use isinstance() for checks, and remember that bool is a kind of int. Annotations document intent but do not enforce it.
Exercise
What does the following code print, and why? x = 10 x = x / 2 print(type(x)._name_, isinstance(x, int))
Show answer
It prints "float False". The expression x / 2 uses true division, which always returns a float, so x is rebound to the float 5.0. Since 5.0 is a float object and not an int, isinstance(x, int) is False, even though the value equals the integer 5.
Exercise
A function must accept an int but reject True and False. Which check do you write, and why does a plain isinstance(value, int) check fail to do this?
Show answer
Check for bool first, for example "if isinstance(value, bool): raise TypeError(...)", then "isinstance(value, int)". A plain isinstance(value, int) accepts True and False because bool is a subclass of int. Alternatively, "type(value) is int" accepts only exact ints and rejects bools.