Introspection is the ability to examine an object at runtime. Python has a dir()
function that supports examining the attributes of an object, type()
to check the object type, isinstance()
, etc.
While introspection is passive examination of the objects, reflection is a more powerful tool where we could modify objects at runtime and access them dynamically. E.g.
setattr()
adds or modifies an object’s attribute;getattr()
gets the value of an attribute of an object.
It can even invoke functions dynamically:
getattr(my_obj, "my_func_name")()