In the realm of computer science, introspection is defined as the ability to determine the type of an object at runtime. Since everything in Python is an object, it has vast support for various methods of introspection. This is particularly helpful because it lets the programmer know about all the properties and attributes of an object.
Let’s look at a few of Python’s built-in methods for introspection:
dir()
The dir()
function returns a sorted list of attributes and methods belonging to an object. Consider the example below, which uses the dir()
function to return the names of all the methods that can be applied to a list:
myList = [1,2,3,4,5]print(dir(myList))
type()
The type()
function simply returns an object’s type. Its usage is shown in the code snippet below:
myList = [1,2,3]print(type(myList))num = 5print(type(num))mystr = "educative"print(type(mystr))obj = {}print(type(obj))
hasattr()
The hasattr()
function checks if an object has a given attribute and, depending on the result, returns either true or false. Its usage is shown below:
class student:name = "Adam"age = 19year = "Sophomore"obj = student()print(hasattr(obj, 'name'))print(hasattr(obj, 'gpa'))
Other methods for introspection include, but are not limited to:
callable()
: checks whether or not an object is callable.issubclass()
: checks if a particular class is derived from another class.__doc__
: returns documentation on an object.__name__
: returns the name of the object.sys()
: provides access to system-specific variables and functions. This function allows one to obtain information about the Python environment.More functions for introspection can be found in Python’s inspect
library, here.
Free Resources