Python introspection examples

Aaron 53 Published: 07/15/2024

Python introspection examples

I'd be happy to provide some examples of Python introspection!

What is Introspection?

In programming, introspection refers to the ability of a program to examine and modify its own structure and behavior at runtime. This can include analyzing the source code, inspecting variables and data structures, modifying class attributes, and even rewriting the code itself.

Python Introspection Examples

Here are some examples of Python's introspective capabilities:

Inspecting Functions and Methods

You can use the inspect module to get information about a function or method, such as its source code, arguments, return type, and more:

import inspect

def my_func(x):

return x * 2

print(inspect.getsource(my_func)) # prints the source code of my_func

print(inspect.getfullargspec(my_func)) # gets the function's argument signature

print(inspect.getreturnnoinfo(my_func)) # gets information about the function's return value

Inspecting Class Attributes

You can use the dir() function to get a list of attributes and methods defined on an object:

class MyClass:

def init(self):

self.x = 5

my_obj = MyClass()

print(dir(my_obj)) # prints a list of attributes and methods defined on my_obj

Modifying Class Attributes

You can use the setattr() function to modify an object's attribute at runtime:

class MyClass:

def init(self):

self.x = 5

my_obj = MyClass()

setattr(my_obj, 'y', 10) # sets a new attribute on my_obj

print(my_obj.y) # prints 10

Dynamic Method Invocation

You can use the getattr() function to dynamically invoke an object's method at runtime:

class MyClass:

def init(self):

self.x = 5

def add_one(self, x):

return x + 1

my_obj = MyClass()

print(getattr(my_obj, 'add_one')(2)) # prints 3

Rewriting Code

You can use the exec() function to execute a string as Python code at runtime:

code = "x = 10ny = x * 2"

exec(code) # executes the given code and modifies the variables in the current scope

print(x) # prints 10

print(y) # prints 20

These are just a few examples of Python's introspective capabilities. Introspection can be a powerful tool for debugging, testing, and even developing more advanced programming techniques.

python inspect function

The inspect module in Python provides several useful functions to help you understand and manipulate the behavior of your code. Here are some key features:

getsource: This function retrieves the source code for a given function, class or method.

Example:

import inspect

def my_function():

pass

print(inspect.getsource(my_function))

This will print out the source code for my_function.

getargspec: This function returns information about the arguments of a particular function.

Example:

import inspect

def my_function(x, y):

return x + y

print(inspect.getargspec(my_function))

This will print out details such as the number and names of the function's parameters, whether the function accepts *args or **kwargs, and whether it returns a value.

getmembers: This function returns a list of members (methods or functions) from a given module.

Example:

import inspect

import math

print(inspect.getmembers(math))

This will print out details such as the names and types of each member in the math module.

getmodule: This function returns the module that a given object belongs to.

Example:

import inspect

import math

f = math.sqrt

print(inspect.getmodule(f))

This will print out the name of the module that sqrt is part of (i.e., math).

getsourcefile: This function returns the name of the file where a given object's source code can be found.

Example:

import inspect

import math

f = math.sqrt

print(inspect.getsourcefile(f))

This will print out the name of the file where sqrt is defined (e.g., math.cpython-37m-darwin.so).

getlineno: This function returns the line number in the source code for a given object.

Example:

import inspect

import math

f = math.sqrt

print(inspect.getlineno(f))

This will print out the line number where sqrt is defined (e.g., 23).

getdoc: This function returns a docstring for a given object.

Example:

import inspect

import math

f = math.sqrt

print(inspect.getdoc(f))

This will print out any docstrings associated with sqrt.

getfullargspec: This function is similar to getargspec, but returns more detailed information about the arguments of a particular function.

Example:

import inspect

def my_function(x, *, y):

return x + y

print(inspect.getfullargspec(my_function))

This will print out details such as the number and names of the function's parameters, whether the function accepts *args or **kwargs, and whether it returns a value.

getmembers: This function is similar to getmembers, but allows you to filter the members based on a specific criteria (e.g., only include methods that start with a certain letter).

Example:

import inspect

import math

members = inspect.getmembers(math, predicate=inspect.isfunction)

print(members)

This will print out details such as the names and types of each function in the math module.

In conclusion, the inspect module provides several useful functions to help you understand and manipulate the behavior of your code. These functions can be used for tasks such as debugging, testing, or simply understanding how your code works.