Introspection in Python
Bhaskar S | 08/10/2014 |
Introduction
Every entity in Python is an object, be it a module, a package, a class, a method, or a type. Introspection is an ability to look into an object (modules, classes, methods, etc) in memory and glean information (or manipulate information) dynamically at run-time.
In this article, we will explore introspection using a simple example to perform the following:
Load a module dynamically at run-time using a module name
Create an instance of a class dynamically at run-time using a class name
Invoke a method of a class dynamically at run-time using a method name
Access the value of a class attribute dynamically at run-time using an attribute name
The following is a simple python module named MyContact.py that defines a class called MyContact:
To dynamically load a python module at run-time, use the import_module method from the standard importlib python module.
The import_module(name, package=None) method takes as arguments a module name and an optional package name.
If the specified module name does not exist, an ImportError exception is thrown.
The following is the python code snippet to dynamically load a specified module:
To check a python object (module or class) at run-time for existence of a named attribute (class, method, or field), use the standard hasattr method.
The hasattr(object, name) method takes as arguments an object (module or class) and an attribute name.
If the specified attribute name does not exist, the method returns a False.
The following is the python code snippet to dynamically check for a specified method:
To get the value of a named attribute (class, method, or field) at run-time, use the standard getattr method.
The getattr(object, name) method takes as arguments an object (module or class) and an attribute name.
If the named attribute is for a field, the result is the value of that field.
If the specified named attribute does not exist, an AttributeError exception is thrown.
The following is the python code snippet to dynamically get the value of a specified field:
Putting it all together, the following is a simple python script named MyDynamic.py that dynamically loads the python module MyContact.py, creates a instance of the class MyContact, invokes the method getEmail(), and gets the value of the field mobile:
Executing MyDynamic.py results in the following output:
Email: john.doe@space.com, Home: 123-456-7890, Mobile: 987-654-3210 Email: john.doe@space.com Mobile: 987-654-3210
References