How to Check If an Object Is of a Given Type in Python

Created
Modified

Using isinstance Method

The isinstance(object, classinfo) method returns True if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof.

Use isinstance to check if o is an instance of str or any subclass of str:

#!/usr/bin/python3

o = "Hello"
print(isinstance(o, str))
True

If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.

Using type Method

To check if the type of o is exactly str, excluding subclasses of str:

#!/usr/bin/python3

o = "Hello"

if type(o) is str:
  print("string")

# Another alternative to the above:
if issubclass(type(o), str):
  print("subclass")
string
subclass

List of classinfo Types

list of strings:

#!/usr/bin/python3

print([t.__name__ for t in __builtins__.__dict__.values() if isinstance(t, type)])
[
  'BuiltinImporter',
  'bool',
  'memoryview',
  'bytearray',
  'bytes',
  'classmethod',
  'complex',
  'dict',
  'enumerate',
  'filter',
  'float',
  'frozenset',
  'property',
  'int',
  'list',
  'map',
  'object',
  'range',
  'reversed',
  'set',
  'slice',
  'staticmethod',
  'str',
  'super',
  'tuple',
  'type',
  'zip',
  'BaseException',
  'Exception',
  'TypeError',
  'StopAsyncIteration',
  'StopIteration',
  'GeneratorExit',
  'SystemExit',
  'KeyboardInterrupt',
  'ImportError',
  'ModuleNotFoundError',
  'OSError',
  'OSError',
  'OSError',
  'EOFError',
  'RuntimeError',
  'RecursionError',
  'NotImplementedError',
  'NameError',
  'UnboundLocalError',
  'AttributeError',
  'SyntaxError',
  'IndentationError',
  'TabError',
  'LookupError',
  'IndexError',
  'KeyError',
  'ValueError',
  'UnicodeError',
  'UnicodeEncodeError',
  'UnicodeDecodeError',
  'UnicodeTranslateError',
  'AssertionError',
  'ArithmeticError',
  'FloatingPointError',
  'OverflowError',
  'ZeroDivisionError',
  'SystemError',
  'ReferenceError',
  'MemoryError',
  'BufferError',
  'Warning',
  'UserWarning',
  'EncodingWarning',
  'DeprecationWarning',
  'PendingDeprecationWarning',
  'SyntaxWarning',
  'RuntimeWarning',
  'FutureWarning',
  'ImportWarning',
  'UnicodeWarning',
  'BytesWarning',
  'ResourceWarning',
  'ConnectionError',
  'BlockingIOError',
  'BrokenPipeError',
  'ChildProcessError',
  'ConnectionAbortedError',
  'ConnectionRefusedError',
  'ConnectionResetError',
  'FileExistsError',
  'FileNotFoundError',
  'IsADirectoryError',
  'NotADirectoryError',
  'InterruptedError',
  'PermissionError',
  'ProcessLookupError',
  'TimeoutError'
]

Related Tags

#check# #type#