The type() Function
type() tells you which type a value has.
Syntax
type(value)The built-in type() function returns the type of a value. It is useful for checking what you are working with.
Common results
type(42)→<class 'int'>type(3.14)→<class 'float'>type('hi')→<class 'str'>type(True)→<class 'bool'>
To test a type in an if, prefer isinstance(value, int), which also respects inheritance.
Example
print(type(42))
print(type(3.14))
print(type('hi'))
print(isinstance(5, int))
# Output:
# <class 'int'>
# <class 'float'>
# <class 'str'>
# TrueWhen to use it
- A debugging session uses type() to confirm a function is returning the expected data type.
- An API handler checks isinstance() before processing a field to avoid attribute errors.
- A data pipeline validates that each column value matches the expected type before writing to a database.
More examples
Check types with type()
Shows how type() reveals the class of any Python object.
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type('hello')) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>isinstance() for type checking
Uses isinstance() to guard a function against wrong input types before processing.
def double(value):
if not isinstance(value, (int, float)):
raise TypeError('Expected a number')
return value * 2
print(double(5)) # 10
print(double(2.5)) # 5.0Dynamic typing in action
Demonstrates that Python variables can change type at runtime (dynamic typing).
x = 10
print(type(x)) # <class 'int'>
x = 'now a string'
print(type(x)) # <class 'str'>
x = [1, 2, 3]
print(type(x)) # <class 'list'>
Discussion