The type() Function

type() tells you which type a value has.

Syntaxtype(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

Example · python
print(type(42))
print(type(3.14))
print(type('hi'))
print(isinstance(5, int))

# Output:
# <class 'int'>
# <class 'float'>
# <class 'str'>
# True

When 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.

Example · python
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.

Example · python
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.0

Dynamic typing in action

Demonstrates that Python variables can change type at runtime (dynamic typing).

Example · python
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

  • Be the first to comment on this lesson.