Skip to main content

Code Introspection in Python

Introspection is an act of self-examination. It is the ability to examine classes, functions and keywords to know what they are, what they do and what they know.

It is used for examining the classes, methods, objects, modules, keywords to get information about them so that we can utilize it. Introspection reveals useful information about objects. Python is a dynamic, object-oriented programming language, that provides tremendous introspection support. It support for introspection runs deep and wide throughout the language. Python provides some built-in functions that are used for code introspection, they are:

1. type()

In this function return which type of an object. 

a = [1,2,3,4,"abc"]
print(type(a))
print(type(a[0]))
print(type(a[4]))

Output:

<class 'list'>
<class 'int'>
<class 'str'>

2. dir()

It return list of methods and attributes associated with the particular  object.

a = ['a','b','c','d']
print(dir(a))

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 
'__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', 
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', 
'__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 
'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 
'remove', 'reverse', 'sort']

3. str()

It is used to convert everything into a string.

a = 3
print(type(a))

a = str(a)
print(a)

print(type(a))

Output:

<class 'int'>
3
<class 'str'>

4. id()

It is used to return a special id assigned to the object.

a = [1,2,3,4,5]
print(id(a))

Output: 140426128161216

Tags
Submitted by devanshi.srivastava on August 3, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.