{"id":337,"date":"2023-07-31T14:22:06","date_gmt":"2023-07-31T14:22:06","guid":{"rendered":"http:\/\/python.garden\/?p=337"},"modified":"2023-08-07T16:17:31","modified_gmt":"2023-08-07T16:17:31","slug":"a-comprehensive-guide-to-object-introspection-and-retrospection-in-python","status":"publish","type":"post","link":"https:\/\/python.garden\/index.php\/2023\/07\/31\/a-comprehensive-guide-to-object-introspection-and-retrospection-in-python\/","title":{"rendered":"A Comprehensive Guide to Object Introspection and Retrospection in Python"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Python, a dynamic, interpreted language, is well-known for its strong reflection and introspection capabilities. Reflection in Python refers to the ability of a program to examine its own structure, particularly through types and attributes, at runtime. This article will walk you through introspection and retrospection in Python, providing practical examples for each.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is Introspection?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Introspection in Python refers to the ability to determine the type of an object at runtime. This feature is beneficial in scenarios where we need to understand an object&#8217;s properties or methods.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Python provides several built-in functions and modules to perform introspection. Here are a few:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">type()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>type()<\/code> function is one of the simplest forms of introspection, returning the type of the object.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">x = [1, 2, 3]\nprint(type(x))  # prints &quot;&lt;class 'list'&gt;&quot;<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">dir()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>dir()<\/code> function is used to find out which attributes or methods an object has.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">x = [1, 2, 3]\nprint(dir(x))<\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">The above code returns a list of all the attributes and methods that belong to the list object &#8216;x&#8217;.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">isinstance()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>isinstance()<\/code> function checks if an object is an instance of a particular class or a subclass thereof.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">x = [1, 2, 3]\nprint(isinstance(x, list))  # prints &quot;True&quot;<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\">inspect module<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Python provides an <code>inspect<\/code> module for advanced introspection. This module provides several functions to help get information about live objects such as modules, classes, and functions.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">import inspect\nprint(inspect.getmembers(str))  # get all members of the string class<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">What is Retrospection?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">While introspection is about understanding objects at runtime, retrospection goes a step further. It&#8217;s about looking back at the object&#8217;s history &#8211; what the object was and what it has become over time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Retrospection in programming, particularly in Python, is not as commonly discussed as introspection, largely due to the dynamic nature of the language. While we can&#8217;t directly track the state changes of an object in Python, we can create a wrapper class to record its history.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example of a basic retrospection:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:true,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}\">class Retrospection:\n    def __init__(self, input_obj):\n        self.history = []\n        self.input_obj = input_obj\n\n    def change(self, new_obj):\n        self.history.append(self.input_obj)\n        self.input_obj = new_obj\n\n    def undo(self):\n        if self.history:\n            self.input_obj = self.history.pop()\n        else:\n            print(&quot;No history available&quot;)\n\n    def get_history(self):\n        return self.history\n\n\nretro = Retrospection(5)\nretro.change(10)\nretro.change(15)\nprint(retro.get_history())  # prints &quot;[5, 10]&quot;<\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">In this code, we have a <code>Retrospection<\/code> class that wraps an object. It keeps track of all changes made to the object through the <code>change()<\/code> method. You can undo the last change with <code>undo()<\/code> and retrieve the history with <code>get_history()<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Introspection and retrospection are powerful tools in Python, enabling you to write dynamic and adaptable code. Understanding these concepts will allow you to exploit Python&#8217;s dynamic nature to its fullest, resulting in more flexible and efficient code.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python, a dynamic, interpreted language, is well-known for its strong reflection and introspection capabilities. Reflection in Python refers to the ability of a program to examine its own structure, particularly&hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[214,213],"tags":[],"class_list":["post-337","post","type-post","status-publish","format-standard","hentry","category-beginners-guide","category-python"],"featured_image_src":null,"author_info":{"display_name":"shababdoo","author_link":"https:\/\/python.garden\/index.php\/author\/shababdoo\/"},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/posts\/337","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/comments?post=337"}],"version-history":[{"count":0,"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/posts\/337\/revisions"}],"wp:attachment":[{"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/media?parent=337"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/categories?post=337"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/python.garden\/index.php\/wp-json\/wp\/v2\/tags?post=337"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}