inspection
type()
Returns the type of an object, or dynamically creates a new type when called with three arguments. type(x) is the runtime class of x.
type(object) | type(name, bases, dict) Parameters
| Parameter | Purpose |
|---|---|
| object | Return the class of this object |
| name/bases/dict | 3-arg form: create a new class programmatically |
Examples
type(42) Returns <class 'int'>
type('x') is str Returns True
type(x) == list Exact type check (ignores subclasses)
Gotcha
type(x) == C rejects subclasses — use isinstance() for polymorphic checks. Prefer 'is' over '==' for type comparisons.
Related built-ins
isinstance()
Returns True if the object is an instance of classinfo (a class or tuple of classes). Respects the class hierarchy — subclasses count.
hasattr()
Returns True if the object has an attribute with the given name. Implemented by calling getattr() and catching AttributeError.
getattr()
Returns the value of the named attribute of object. If the attribute is missing, returns default (if given) or raises AttributeError.
len()
Returns the number of items in a container. Calls the object's __len__ method.