Object Introspection

In today’s tutorial, we are going to learn about object introspection. We have used it a bit in our previous tutorial but never discussed it in depth. As we have discussed earlier that everything in Python is an object. All the functions we use regularly are predefined in some built-in class. For example, while printing any string, we are using the object of an str class that is predefined for the usage of string.

Object Introspection in Python:

Introspection can be said as the ability to recognize the object along with all its details, such as id or location at runtime. One of the most basic introspects we came across many times earlier is type()

type(object)

We used it to see the type of our object, that whether it is int, float, or string. We have to pass the object in the parenthesis, and the compiler will return the type. Introspection gives us useful information about the program’s objects. Python provides tremendous introspection support. Introspection is the ability to determine the type of an object at runtime. Hence, by using introspection, we can inspect the Python objects dynamically.

There are many types of introspections. In this tutorial, we will focus on three of them to get a brief idea about their working. You may search the internet for more, but we will be focusing on three for conceptual learning. We have already discussed type( ), now let’s move onto id( ). Id provides us with the id allocated to the particular object. The id of each object is unique, meaning it is different, and no two objects can have the same id. 

id(object)

Now the most important introspection function is dir(). It returns us a list of attributes and methods associated with an object. By using dir(), we can check the attributes that our object is composed of. It is mostly executed before and after updating our object by inserting more attributes or methods. 

o = MyClass()
print(dir(o))

Types of introspects:-

Some of the other common Introspects:

 FunctionsWorking
hasattr()It checks if an object has an attribute.
getattr()It returns the contents of an attribute if there are some.
repr()It returns the string representation of an object
vars()It checks all the instance variables of an object
issubclass()This function checks that if a specific class is a derived class of another class.
isinstance()It checks if an object is an instance of a specific class. 
__doc__This attribute gives some documentation about an object 
__name__This attribute holds the name of the object
callable()This function checks if an object is a function
help()It checks what other functions do

So, this was all about object introspection in Python. I hope you are enjoying this course. If yes, then please share this course with your friends and family also. I will see you in the next tutorial. Till then, keep coding and keep learning.

Code as described/written in the video:


class Employee:
    def __init__(self, fname, lname):
        self.fname = fname
        self.lname = lname
        # self.email = f"{fname}.{lname}@codewithharry.com"

    def explain(self):
        return f"This employee is {self.fname} {self.lname}"

    @property
    def email(self):
        if self.fname==None or self.lname == None:
            return "Email is not set. Please set it using setter"
        return f"{self.fname}.{self.lname}@codewithharry.com"

    @email.setter
    def email(self, string):
        print("Setting now...")
        names = string.split("@")[0]
        self.fname = names.split(".")[0]
        self.lname = names.split(".")[1]

    @email.deleter
    def email(self):
        self.fname = None
        self.lname = None


skillf = Employee("Skill", "F")
# print(skillf.email)
o = "this is a string"
# print(dir(skillf))
# print(id("that that"))
import inspect
print(inspect.getmembers(skillf))

Python inspect module functionalities

  • Introspection of a module =  module using inspect.getmembers()                           
  • Introspection of classes in a module =The getmembers() function along with the isclass property identifier is used to inspect the classes within a module.
  • Introspection of methods/functions in a class =The getmembers() function along with the isfunction property identifier is used to inspect the classes within a module.
  • Introspection of objects of a class =getmembers() with inspect.ismethod
  • Retrieval of source of a class = The getsource() functions returns the source of a particular module/class.
  • Retrieval of source of a method/function = The getsource() functions returns the source of a particular module/class.
  • Fetching the method signature = The inspect.signature() method returns the signature of the method, thus making it easy for the user to understand the kind of arguments passed to the method.
  • Documentation of Strings for a class = The inspect module’s getdoc() function extracts a particular class and its functions to represent to the end-user.
  • Introspecting Class Hierarchies = The getclasstree() method returns the hierarchy of the classes and its dependencies. It creates a tree-structure using tuples and lists from the given classes.
  • Introspection of Frames and Stacks in the run-time environment = The inspect module also inspects the function’s dynamic environment of the program during its execution. The functions mostly work with call stack and call frames.

    currentframe() depicts the frame at the top of the stack for the current executing function. getargvalues() results as a tuple with the names of the arguments, and a dicttionary of local values from the frames.





Comments

Popular posts from this blog

HOW IMPORT WORKS IN PYTHON?

Exercise 5: Health Management System

*args and **kwargs In Python