Introspection of the Python code

In this tutorial, we will learn about the introspection of the Python code. Introspection refers to the ability to determine the properties related to objects at runtime. We will discuss ways of introspection in Python in detail here.

There are many built-in methods in Python that can be used for introspection. Some of these have been explained below with examples.

  • ¬†type(): This function returns the type of an object passed as a parameter. Have a look at the code to understand.
    import sys
    print(type(sys))
    
    num = 12.5
    print(type(num))
    
    tup = (2,3,4)
    print(type(tup))
    

    Output:

    <class 'module'>
    <class 'float'>
    <class 'tuple'>
  • str(): str() function converts the objects that is passed into a string. The below example program will clear any doubt. See the code.
    num = 12.5
    num = str(num)
    print(type(num))
    
    tup = (2,3,4)
    tup = str(tup)
    print(type(tup))
    

    Output:

    <class 'str'>
    <class 'str'>
  • dir(): This built-in Python function returns a list of attributes and methods for an object. Have a look at the code.
    set = {1, 4, 6, 8}
    
    print(dir(set))
    

    Output:

    ['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
  • help(): This function returns the documentation for an object. This consists of the details of what functions do in the program.
    #help for print
    help(print)
    

    Executing this will generate a help page for the print object on the console.

  • id(): This built-in function returns the id of an object. This id is unique for every object during the lifetime of a Program.
    num = 12.5
    print(id(num))
    
    tup = (2,3,4)
    print(id(tup))
    

    Output:

    1834524582176
    1834557759280

Other useful methods for introspection in python are:

Thank you.

Leave a Reply