Back to Python
2026-02-255 min read

Introspection Functions (Python Programming)

Learn Introspection Functions (Python Programming) step by step with clear examples and exercises.

Title: Introspection Functions (Python Programming)

Why This Matters

Introspection functions are a crucial aspect of Python that allow you to inspect and manipulate objects at runtime, such as variables, classes, modules, and more. Understanding these functions is essential for debugging, code optimization, and developing complex applications. They can help you understand the structure of your program, find errors, and even automate certain tasks.

Prerequisites

Before diving into introspection functions, it's important to have a good understanding of:

  1. Python syntax and data types
  2. Functions and modules in Python
  3. Basic object-oriented programming concepts (classes and instances)
  4. Exception handling
  5. Understanding the Python built-in dir() function
  6. Familiarity with Python's control structures, such as loops and conditionals
  7. Knowledge of Python's error handling mechanisms, including exceptions and tracebacks

Core Concept

Introspection functions are a set of built-in Python functions that help you understand the structure, attributes, and methods of objects at runtime. Some common introspection functions include:

  1. type(): Returns the type of an object (e.g., int, str, list, dict, etc.)
  2. isinstance(): Checks if an object is an instance of a specific class or subclass
  3. vars(): Returns a dictionary containing all attributes and their values for an object (not applicable to built-in types like lists and dictionaries)
  4. hasattr(): Checks if an object has a specific attribute
  5. getattr(): Retrieves the value of an attribute by its name
  6. setattr(): Sets the value of an attribute by its name
  7. delattr(): Deletes an attribute by its name
  8. dir(): Returns a list of an object's attributes and methods (including inherited ones)
  9. locals(): Returns a dictionary containing all local variables in the current scope
  10. globals(): Returns a dictionary containing all global variables in the current module

Here's a simple example demonstrating some introspection functions:

class MyClass:
def __init__(self, name):
self.name = name

def my_method(self):
print("Hello, {}!".format(self.name))

my_obj = MyClass("John")

Check the type of my_obj using type()

print(type(my_obj)) #

Check if my_obj has a 'name' attribute using hasattr()

print(hasattr(my_obj, "name")) # True

Retrieve and print the value of the 'name' attribute using getattr()

print("Name:", getattr(my_obj, "name")) # Name: John

Call my_obj's method using getattr()

getattr(my_obj, "my_method")() # Hello, John!

Set a new attribute for my_obj using setattr()

setattr(my_obj, "age", 30)

Print all attributes and methods for my_obj using dir()

print("Attributes and Methods:", dir(my_obj))

Worked Example

Let's create a simple Python program that uses introspection functions to inspect and manipulate an object. We will define a class Person with attributes name, age, and salary. Then, we'll use various introspection functions to explore the object and make changes to its properties.

class Person:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary

def display_info(self):
print("Name:", self.name)
print("Age:", self.age)
print("Salary:", self.salary)

Create a new instance of Person with the given attributes

person = Person("Alice", 25, 60000)

Print the type of person using type()

print(type(person)) #

Check if person has specific attributes using hasattr()

print(hasattr(person, "name")) # True

print(hasattr(person, "salary")) # True

Retrieve the values of the 'name' and 'salary' attributes using getattr()

name = getattr(person, "name")

salary = getattr(person, "salary")

print("Name:", name) # Name: Alice

print("Salary:", salary) # Salary: 60000

Raise an AttributeError to demonstrate exception handling

try:

print(getattr(person, "address")) # This will raise an AttributeError

except AttributeError as e:

print("AttributeError:", e) # AttributeError: 'Person' object has no attribute 'address'

Set a new attribute called 'area' that calculates the area of a rectangle (using the formula width * height)

width = 5

height = 10

setattr(person, "area", width * height)

Print all attributes and methods for person using dir()

print("Attributes and Methods:", dir(person))

Common Mistakes

  1. Forgetting to import the necessary modules (e.g., from __future__ import print_function)
  2. Misusing or misunderstanding the purpose of introspection functions (e.g., using hasattr() to check if an object is a specific type instead of checking for attributes)
  3. Not handling exceptions properly when dealing with missing or undefined attributes
  4. Assuming that all objects have the same set of attributes and methods, leading to unexpected behavior
  5. Misunderstanding the difference between instance variables and class variables (e.g., using setattr() on a class instead of an instance)
  6. Failing to consider the order of attribute assignment or modification, which can lead to unintended side effects
  7. Overuse of introspection functions for tasks that could be more efficiently accomplished with other methods

Practice Questions

  1. Write a Python script that defines a class Rectangle with attributes width and height. Use introspection functions to:
  • Check if the object has a 'width' attribute
  • Retrieve the value of the 'width' attribute
  • Set a new attribute called 'area' that calculates the area of the rectangle (using the formula width * height)
  1. Write a Python script that defines a class Car with attributes make, model, and year. Use introspection functions to:
  • Check if the object has a 'make' attribute
  • Retrieve the value of the 'make' attribute
  • Set a new attribute called 'mileage' that calculates the total mileage based on the current year (assume 15,000 miles per year)
  1. Write a Python script that defines a class BankAccount with attributes balance, interest_rate, and account_number. Use introspection functions to:
  • Check if the object has a 'balance' attribute
  • Retrieve the value of the 'balance' attribute
  • Calculate the monthly interest using the formula balance * (interest\_rate / 12) and add it to the balance
  • Print the updated balance

FAQ

  1. Why should I use introspection functions instead of directly accessing object attributes?
  • Introspection functions provide a more flexible and dynamic way to interact with objects, allowing you to inspect and manipulate them at runtime without knowing their exact structure beforehand.
  1. What's the difference between hasattr(), getattr(), and dir() in Python?
  • hasattr() checks if an object has a specific attribute, getattr() retrieves the value of an attribute by its name, and dir() returns a list of all attributes and methods for an object.
  1. Can I use introspection functions on built-in types like lists and dictionaries?
  • Not directly, as these built-in types do not have the same structure as user-defined classes or instances. However, you can still use type() to check their type and access their methods using dir().
  1. What is the purpose of the locals() and globals() functions?
  • locals() returns a dictionary containing all local variables in the current scope, while globals() returns a dictionary containing all global variables in the current module. These functions can be useful for iterating over variables or accessing variables that are not directly accessible due to scoping rules.
  1. What's the difference between setattr(), delattr(), and del() in Python?
  • setattr() sets an attribute for an object, delattr() deletes an attribute for an object, and del is a statement used to delete variables or objects in Python. The main difference lies in their usage: setattr() and delattr() are functions that operate on objects, while del is a statement that operates on variables.
Introspection Functions (Python Programming) | Python | XQA Learn