Python type function
last modified November 30, 2026 Python 3.15
In this article we show how to find out the type of a value at run time
with the type function, and how to use types in our
programs.
Every value in Python has a type, which decides what operations the
value supports. Variables have no fixed type; the same variable can
refer to an integer now and to a string later. The built-in
type function, called with one argument, returns the type
of a value. The types of the basic values are described in
Python data types.
The type function also has a three-argument form that
creates new classes. It is covered in the
type builtin function article.
The type of a value
We start by printing the types of a few literal values.
values = [42, 3.14, 'sky', True, None, [1, 2], (1, 2), {'a': 1}]
for value in values:
print(repr(value), type(value))
The loop prints each value next to its type.
print(repr(value), type(value))
A type is printed as <class 'int'>: in Python, types
and classes are the same thing. The repr function shows
strings with quotes, so that we can tell 'sky' from a
name.
$ python first.py
42 <class 'int'>
3.14 <class 'float'>
'sky' <class 'str'>
True <class 'bool'>
None <class 'NoneType'>
[1, 2] <class 'list'>
(1, 2) <class 'tuple'>
{'a': 1} <class 'dict'>
Types are objects
The value returned by type is an object like any other.
It can be stored in a variable, compared, and called.
t = type(3.14)
print(t)
print(t.__name__)
print(t is float)
print(t('2.5') + 1)
print(type(int))
print(type(type(3.14)))
number_types = [int, float, complex]
for nt in number_types:
print(nt.__name__, nt('7'))
The program works with type objects directly.
t = type(3.14) print(t) print(t.__name__) print(t is float)
The result of type(3.14) is the built-in
float type, the same object that the name
float refers to. The __name__ attribute holds
the name of the type as a string.
print(t('2.5') + 1)
Calling a type creates a value of that type. Here it converts a string to a float.
print(type(int))
The type of a type is type.
number_types = [int, float, complex]
for nt in number_types:
print(nt.__name__, nt('7'))
Types can be stored in a list and used in a loop like other values.
$ python type_objects.py <class 'float'> float True 3.5 <class 'type'> <class 'type'> int 7 float 7.0 complex (7+0j)
Comparing types
The result of type can be compared with a type using the
is operator.
def describe(value):
if type(value) is int:
return 'whole number'
elif type(value) is float:
return 'decimal number'
elif type(value) is str:
return 'text'
else:
return 'something else: ' + type(value).__name__
print(describe(10))
print(describe(2.5))
print(describe('ten'))
print(describe([10]))
print(type(10) == type(20))
print(type(10) is type(20.0))
The describe function returns a description based on the
type of its argument.
if type(value) is int:
return 'whole number'
Each type exists only once, so the identity test is is
the right comparison. The == operator gives the same
result for types, but is states the intent more clearly.
return 'something else: ' + type(value).__name__
For values of other types, we include the name of the type in the description.
$ python comparing.py whole number decimal number text something else: list True False
type versus isinstance
The type(x) is T test matches only the exact type. The
isinstance function also accepts subclasses, that is,
types derived from T.
class Temperature(float):
pass
t = Temperature(21.5)
print(type(t) is float, isinstance(t, float))
print(type(True) is int, isinstance(True, int))
print(True + True)
def is_count(value):
return isinstance(value, int) and not isinstance(value, bool)
for value in [3, True, 3.0, '3']:
print(repr(value), isinstance(value, int), is_count(value))
The Temperature class is a subclass of
float; its values are floats with a different type.
print(type(t) is float, isinstance(t, float))
The exact type of t is Temperature, so the
type test fails, while isinstance succeeds.
In most code, isinstance is the better choice, because a
subclass is meant to work wherever its base type works.
print(type(True) is int, isinstance(True, int)) print(True + True)
The built-in bool type is a subclass of
int; True behaves like 1 and
False like 0.
def is_count(value):
return isinstance(value, int) and not isinstance(value, bool)
When a function must accept integers but reject booleans, we exclude
bool explicitly.
$ python type_vs_isinstance.py False True False True 2 3 True True True True False 3.0 False False '3' False False
Checking several types
The isinstance function accepts a tuple of types or a
union written with the | operator.
def is_number(value):
return isinstance(value, (int, float)) and not isinstance(value, bool)
print(is_number(4), is_number(4.5), is_number('4'), is_number(False))
Number = int | float
print(Number)
print(isinstance(4.5, Number), isinstance('4.5', Number))
print(isinstance(None, str | None))
print(type(7) in (int, float))
The program checks for numbers in three ways.
return isinstance(value, (int, float)) and not isinstance(value, bool)
With a tuple, isinstance returns True if the
value is an instance of any of the types.
Number = int | float
print(Number)
print(isinstance(4.5, Number), isinstance('4.5', Number))
The expression int | float creates a union type object,
which can be stored in a variable and passed to
isinstance.
print(isinstance(None, str | None))
In a union, None stands for its type,
NoneType. This checks for an optional string.
print(type(7) in (int, float))
For an exact check against several types, we use the
in operator with a tuple of types.
$ python several_types.py True True False False int | float True False True True
Converting to the type of another value
Since a type can be called, type(x)(...) creates a value
of the same type as x. In the next example, settings read
as text are converted to the types of their default values.
defaults = {
'port': 8080,
'ratio': 0.75,
'name': 'server',
}
settings = {'port': '9000', 'ratio': '0.5', 'name': 'backup'}
config = {}
for key, default in defaults.items():
text = settings.get(key)
if text is None:
config[key] = default
else:
config[key] = type(default)(text)
for key, value in config.items():
print(f'{key:6} {value!r:10} {type(value).__name__}')
The defaults dictionary defines the settings and their
types; the settings dictionary contains strings, as if
read from a file or the command line.
config[key] = type(default)(text)
For the port key, type(default) is
int, so the line calls int('9000'). The same
line converts the ratio with float and keeps the name as
a string. Adding a new setting needs no new conversion code.
$ python converting.py port 9000 int ratio 0.5 float name 'backup' str
An empty value of the same type
Calling a type without arguments returns an empty or zero value of that type. This lets a function return a result of the same type it received.
def first_half(seq):
result = type(seq)()
for i in range(len(seq) // 2):
result += seq[i:i + 1]
return result
print(first_half([1, 2, 3, 4]))
print(first_half((1, 2, 3, 4)))
print(first_half('python'))
print(repr(type('abc')()), type([1])(), type(5)(), type(2.5)())
The first_half function returns the first half of a list,
tuple, or string.
result = type(seq)()
for i in range(len(seq) // 2):
result += seq[i:i + 1]
The result starts as an empty list, tuple, or string. A slice of a sequence has the same type as the sequence, so it can be added to the result.
print(repr(type('abc')()), type([1])(), type(5)(), type(2.5)())
The empty values are '', [], 0,
and 0.0.
$ python empty_value.py [1, 2] (1, 2) pyt '' [] 0 0.0
Dispatching on the type
Types can be dictionary keys. A dictionary that maps types to functions
replaces a long if/elif chain.
def show_int(value):
return f'{value:,}'
def show_float(value):
return f'{value:.2f}'
def show_list(value):
return f'{len(value)} items'
formatters = {int: show_int, float: show_float, list: show_list}
for value in [1234567, 3.14159, [1, 2, 3], 'text', True]:
fmt = formatters.get(type(value), repr)
print(type(value).__name__, '->', fmt(value))
Each type gets its own formatting function.
fmt = formatters.get(type(value), repr)
We look up the formatter by the exact type of the value and fall back
to repr. A lookup by exact type ignores subclasses:
True is not formatted as an integer, because
bool is not a key in the dictionary. The
functools.singledispatch decorator builds such dispatch
tables and also handles subclasses.
$ python dispatch.py int -> 1,234,567 float -> 3.14 list -> 3 items str -> 'text' bool -> True
Matching types with match
A match statement can test types
with class patterns such as int(). A class pattern works
like isinstance.
def describe(value):
match value:
case bool():
return f'flag {value}'
case int() | float():
return f'number {value}'
case str() if value:
return f'text {value!r}'
case str():
return 'empty text'
case None:
return 'nothing'
case _:
return f'unknown {type(value).__name__}'
for value in [True, 7, 2.5, 'sky', '', None, [1]]:
print(describe(value))
The describe function handles several types.
case bool():
return f'flag {value}'
case int() | float():
return f'number {value}'
Because True is also an int, the
bool() case must come first. The | operator
combines two patterns.
case str() if value:
return f'text {value!r}'
case str():
return 'empty text'
A guard adds a condition to the type test.
case None:
return 'nothing'
None is matched as a value, since there is only one.
$ python match_types.py flag True number 7 number 2.5 text 'sky' empty text nothing unknown list
Types in error messages
When a function rejects an argument, the error message should name the
type it received. The usual way is type(value).__name__.
def area(width, height):
for name, value in [('width', width), ('height', height)]:
if not isinstance(value, (int, float)):
kind = type(value).__name__
raise TypeError(f'{name} must be a number, not {kind}')
return width * height
print(area(3, 4.5))
try:
area(3, '4')
except TypeError as e:
print(e)
print(3 * '4')
The area function accepts integers and floats.
kind = type(value).__name__
raise TypeError(f'{name} must be a number, not {kind}')
The TypeError exception is the standard error for an
argument of the wrong type. The message has the same form as the
messages of the built-in functions.
print(3 * '4')
Without the check, a string argument would not always fail: repeating
a string is a valid operation, and area(3, '4') would
return '444'. This is why explicit type checks are useful
at the boundaries of a program.
$ python error_messages.py 13.5 height must be a number, not str 444
Source
type, isinstance, Union type, functools.singledispatch
In this article we have obtained the types of values, used types as
objects and constructors, compared types, chosen between
type and isinstance, checked several types at
once, converted values to the type of another value, dispatched on
types with a dictionary and with match, and reported types
in error messages. See also
Python data types,
Python introspection,
Python isinstance, and
Python type builtin function.
Author
List all Python tutorials.