Skip to content

Module 3 · Variables and Data Types — topic 10 of 15

type()

Use type() and isinstance() to find out what kind of value you have, read type names, and choose the right check when writing functions that accept several types.

Beginner 10 min read·Lesson 38 of 306 in Python Programming

Learning objectives

  • Inspect the type of any value with type()
  • Use isinstance() to check types, including several at once
  • Explain why isinstance() is usually preferred

Definition

Use type() and isinstance() to find out what kind of value you have, read type names, and choose the right check when writing functions that accept several types.

Introduction

type(value) tells you what kind of value you are dealing with: int, float, str, list and so on. It is one of the most useful tools while learning and debugging.

Why it matters

Many bugs come from a value having a different type than you expected, such as a string from input() where you wanted a number. Checking the type quickly shows the problem, and isinstance() lets functions handle different kinds of input correctly.

Detailed explanation

type(x) returns the type object of x, which prints as <class 'int'>. type(x).__name__ gives just the name, such as 'int'.

Type objects can be compared: type(x) is int is True for integers.

isinstance(x, int) is the recommended way to check a type in code. It also accepts a tuple of types: isinstance(x, (int, float)).

isinstance respects inheritance: isinstance(True, int) is True because bool is a kind of int, while type(True) is int is False.

The type names are also the conversion functions you met earlier, so int, str and float serve two roles.

Use type() for exploring and debugging, and isinstance() inside programs that must make decisions based on type.

In many programs you don’t need explicit type checks at all: converting input early and letting a TypeError surface for genuinely wrong values keeps code short. Reach for isinstance() when a function is deliberately designed to accept more than one kind of input and must treat them differently.

Syntax

Python
type(value)
type(value).__name__
isinstance(value, int)
isinstance(value, (int, float))
  • type() returns the value’s class.
  • __name__ gives a readable name.
  • isinstance() checks against one type or a tuple of types.

Code examples

Looking at types

Python
for value in [42, 4.2, "42", True, None, [4, 2]]:
print(repr(value), "->", type(value).__name__)
Output
42 -> int
4.2 -> float
'42' -> str
True -> bool
None -> NoneType
[4, 2] -> list

type vs isinstance with bool

Python
print(type(True) is int)
print(isinstance(True, int))
Output
False
True

More examples

A function that accepts numbers or numeric text

Python
def to_number(value):
if isinstance(value, (int, float)) and not isinstance(value, bool):
return value
if isinstance(value, str) and value.strip().replace(".", "", 1).isdigit():
return float(value) if "." in value else int(value)
raise TypeError(f"cannot use {type(value).__name__}")
for v in [7, 2.5, " 12 ", "3.75"]:
print(repr(v), "->", to_number(v))
try:
to_number(None)
except TypeError as err:
print(err)
Output
7 -> 7
2.5 -> 2.5
' 12 ' -> 12
'3.75' -> 3.75
cannot use NoneType

Step-by-step explanation

  • The first check accepts ints and floats but rejects bools, which are technically ints.
  • The second accepts strings that contain only digits and at most one decimal point.
  • int() and float() both ignore surrounding spaces, so " 12 " works.
  • Anything else raises TypeError with the received type’s name.

Expected output

Running “A function that accepts numbers or numeric text” prints exactly:

TextOutput
7 -> 7
2.5 -> 2.5
' 12 ' -> 12
'3.75' -> 3.75
cannot use NoneType

Practical applications

  • Libraries check argument types to give clear errors instead of failing deep inside.
  • JSON parsing code checks whether a value is a dict, list, str or number before using it.
  • Developers print type(x) while debugging to confirm what a function returned.

Best practices

  • Use type() to explore, isinstance() to decide.
  • Check against a tuple to accept several types.
  • Prefer converting input early over checking types everywhere.

Common mistakes

Comparing type names as strings

Avoid

if str(type(x)) == "int":

Prefer

if isinstance(x, int):

str(type(x)) is "<class 'int'>", so the comparison is always False.

Forgetting bool is an int

Avoid

isinstance(flag, int) # True for True/False too

Prefer

isinstance(flag, int) and not isinstance(flag, bool)

Exclude bool explicitly when only real integers are acceptable.

Key takeaways

  • type() returns a value’s class; __name__ gives its name.
  • isinstance() checks types and respects inheritance.
  • bool is a subclass of int.

Try it yourself

  1. 1
    Write a function that returns "number", "text" or "other" for any value, using isinstance().
  2. 2
    Print the type names of 10 / 2, 10 // 2 and 10 % 3.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic