Low Orbit Flux Logo 2 D

Python How To Check Type

You may find yourself wondering how to check the type of a variable in Python. This is relatively easy to do. Python variables are dynamically typed but they are also strongly typed.

To check the type of a variable in Python just use the following:


type(x)

Here is a more complete example showing how this would work with multiple different types of variables.

You can set a bunch of variables with different types like this:


a = 5
b = "test"
c = True
d = [ 1, 2, 3 ]
e = { "a": "b" }
f = 2.5
g = ( 1, 2 )
h = b"test"

You can print out the types like this:


print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
print(type(g))
print(type(h))

The output will look like this:


<class 'int'>
<class 'str'>
<class 'bool'>
<class 'list'>
<class 'dict'>
<class 'float'>
<class 'tuple'>
<class 'bytes'>

If you actually want to run a check for a certain type you can use the following:


if type(x) is str:

If you want to check if a variable is an instance of a class you can use the following. This also checks if it is an instance of a subclass of the specified class:


if isinstance(x, str):

You can specifically check if a variable is an instance of a subclass:


if issubclass(type(x), str):