{"id":5898,"date":"2020-05-26T10:04:13","date_gmt":"2020-05-26T10:04:13","guid":{"rendered":"https:\/\/www.askpython.com\/?p=5898"},"modified":"2026-09-29T16:33:42","modified_gmt":"2026-09-29T16:33:42","slug":"python-getattr-function","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/built-in-methods\/python-getattr-function","title":{"rendered":"Using the Python getattr() function"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Hello again! In today&#8217;s article, we&#8217;ll be looking at the Python getattr() function in Python.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This function tries to get the attribute of a Python object. This is very similar to the <a href=\"https:\/\/www.askpython.com\/python\/python-setattr-function\" class=\"rank-math-link\">setattr() function<\/a>, but it does not modify the object.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s find out how we can put this function to use, using some simple examples.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Basic Syntax of Python getattr()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The basic syntax of the getattr() function is as follows:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nvalue = getattr(object, attribute_name&#x5B;, default_value])\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Here, we pass <code>object<\/code> to <code>getattr()<\/code>. It tries to fetch <code>attribute_name<\/code> (which must be a string) of this object. If the attribute exists, it will give us the corresponding <code>value<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is equivalent to the syntax:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nvalue = object.attribute_name\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Otherwise, there are two cases:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>If the default value (<code>default_value<\/code>) is provided, it will simply use it and return the value of this default value.<\/li><li>Otherwise, it will simply raise an <code>AttributeError<\/code> Exception, since our attribute is not found.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The point of <code>getattr()<\/code> is to not only get the attribute value, but to also check that it exists!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s now look at a few examples, to better our understanding.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Using getattr() &#8211; Some Examples<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s take a simple example first, where you have a Student class, with <code>name<\/code> and <code>roll_num<\/code> attributes. We&#8217;ll get them using <code>getattr()<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass Student():\n    def __init__(self, name, roll_no):\n        self.name = name\n        self.roll_no = roll_no\n\nstudent = Student(&#039;Amit&#039;, 8)\n\nprint(f&quot;Name: {getattr(student, &#039;name&#039;)}&quot;)\nprint(f&quot;Roll No: {getattr(student, &#039;roll_no&#039;)}&quot;)\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nName: Amit\nRoll No: 8\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Indeed, we did set the correct attributes, and we get them back using <code>getattr()<\/code>!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now, in this case, since both the attributes were there, no errors occurred. However, let&#8217;s try to get an attribute which we haven&#8217;t put inside the class; for example &#8211; <code>age<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass Student():\n    def __init__(self, name, roll_no):\n        self.name = name\n        self.roll_no = roll_no\n\nstudent = Student(&#039;Amit&#039;, 8)\n\nprint(f&quot;Name: {getattr(student, &#039;name&#039;)}&quot;)\nprint(f&quot;Roll No: {getattr(student, &#039;roll_no&#039;)}&quot;)\n\n# Will raise &#039;AttributeError&#039; Exception since the attribute &#039;age&#039; is not defined for our instance\nprint(f&quot;Age: {getattr(student, &#039;age&#039;)}&quot;)\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nName: Amit\nRoll No: 8\nTraceback (most recent call last):\n  File &quot;getattr_example.py&quot;, line 12, in &amp;lt;module&gt;\n    print(f&quot;Age: {getattr(student, &#039;age&#039;)}&quot;)\nAttributeError: &#039;Student&#039; object has no attribute &#039;age&#039;\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Here, we tried to retrieve an attribute which wasn&#8217;t defined. Since there were no default options, Python directly raised an Exception.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If we want to set the default option to <code>'100'<\/code>, then in this case, although we try to get <code>age<\/code>, since it isn&#8217;t there, it will return <code>100 <\/code>instead.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s test it out.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nclass Student():\n    def __init__(self, name, roll_no):\n        self.name = name\n        self.roll_no = roll_no\n\nstudent = Student(&#039;Amit&#039;, 8)\n\nprint(f&quot;Name: {getattr(student, &#039;name&#039;)}&quot;)\nprint(f&quot;Roll No: {getattr(student, &#039;roll_no&#039;)}&quot;)\n\n# Will not raise AttributeError, since a default value is provided\nprint(f&quot;Age: {getattr(student, &#039;age&#039;, 100)}&quot;)\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nName: Amit\nRoll No: 8\nAge: 100\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Why should you use getattr() ?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Since we mentioned earlier that this function is equivalent to <code>object.attribute_name<\/code>, what is the point of this function?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">While the above statement using dot notation is true, it is valid only when the attribute name is actually defined at the time of calling!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So, if your classes are such that the object structure keeps changing from time to time, you could use <code>getattr()<\/code> to check whether the object is in some particular state!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It also gives us a very good way to easily handle exceptions and also provide fallback default values. In case something went wrong, we could either catch the <code>AttributeError<\/code> exception or inspect the default value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Hope that makes it a bit more clearer as to why this may be useful for you!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We learned about how we could use the <code>getattr()<\/code> function to retrieve the attributes of an object during runtime.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/docs.python.org\/3\/library\/functions.html#getattr\" class=\"rank-math-link\" target=\"_blank\" rel=\"noopener\">Python Official Documentation<\/a> on getattr()<\/li><li>JournalDev article on Python getattr()<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n","protected":false},"excerpt":{"rendered":"<p>Hello again! In today&#8217;s article, we&#8217;ll be looking at the Python getattr() function in Python. This function tries to get the attribute of a Python object. This is very similar to the setattr() function, but it does not modify the object. Let&#8217;s find out how we can put this function to use, using some simple [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":67907,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[],"class_list":["post-5898","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-built-in-methods"],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/5898","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=5898"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/5898\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/67907"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=5898"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=5898"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=5898"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}