What is Python introspection?

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 = 5
print(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 = 19
year = "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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved