Python’s built-in type function returns the type of any object. Calling it on 5 produces <class 'int'>; calling it on a list produces <class 'list'>. section 17.1
The result is itself an object: its type is <class 'type'>. Python therefore treats classes and types as objects that can be stored or passed around. section 17.1
Use type alongside related class-inspection tools:
- Inspect an instance with type(obj) or obj.__class__; both identify the class of the instance. section 17.3
- Inspect a class with __name__ and __bases__ to find its name and immediate base classes. section 17.3
- Prefer isinstance for checking whether an object belongs to a class or one of its subclasses, and use issubclass for classes. section 17.3
Inspecting an instance
class A: pass class B(A): pass b = B() type(b) # <class '__main__.B'> b.__class__ # <class '__main__.B'> type(type(b)) # <class 'type'> section 17.3
Capturing a type for validation
class TypedList: def __init__(self, example_element): self.type = type(example_element) x = TypedList('Hello') # x.type is <class 'str'> section 17.8
type(5) <class 'int'> type(['hello', 'goodbye']) <class 'list'>
Compare the values returned by type for an integer and a list. section 17.1


