{"id":1584,"date":"2023-11-13T16:10:44","date_gmt":"2023-11-13T10:40:44","guid":{"rendered":"https:\/\/geekpython.in\/?p=1584"},"modified":"2024-03-01T17:04:27","modified_gmt":"2024-03-01T11:34:27","slug":"understanding-if-__name__-__main__-in-python-programs","status":"publish","type":"post","link":"https:\/\/geekpython.in\/understanding-if-__name__-__main__-in-python-programs","title":{"rendered":"Understanding if __name__ == &#8216;__main__&#8217; in Python Programs"},"content":{"rendered":"\n<p>You may have seen the <code>if __name__ == '__main__':<\/code> along with some code written inside this block in Python script. Have you ever wondered what this block is, and why it is used?<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<p class=\"responsive-video-wrap clr\"><iframe loading=\"lazy\" title=\"Understanding if __name__ == &#039;__main__&#039; in Python | 2MinutesPy\" width=\"1200\" height=\"675\" src=\"https:\/\/www.youtube.com\/embed\/WfPwvUjIZtE?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" allowfullscreen><\/iframe><\/p>\n<\/div><\/figure>\n\n\n\n<p>In this article, you&#8217;ll discover the concept of <code>if __name__ == '__main__'<\/code> block.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding if __name__ == &#8216;__main__&#8217;?<\/h2>\n\n\n\n<p>Well, <code>if __name__ == '__main__':<\/code> is not some magical keyword or incantation in Python rather it is <strong>a way to ensure that specific code is executed when the module is directly executed not when it is imported as a module<\/strong>.<\/p>\n\n\n\n<p>What this expression implies is that only when a certain condition is met, further action should be taken. For example, if the name of the current running module (<code>__name__<\/code>) is the same as <code>\"__main__\"<\/code>, only the code following the <code>if __name__ == '__main__':<\/code> block is executed.<\/p>\n\n\n\n<p>Here&#8217;s a Python script in which a function is defined that returns a square of the value and a print statement that prints the square of the specified integer.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" title=\"math_module.py\"># math_module.py\n\n# Defined a Function\ndef square(num):\n    value = num * num\n    return value\n\nprint(\"Main Script.\")\nresult = square(2)\nprint(f\"Square of 2: {result}.\")\n\n----------\nMain Script.\nSquare of 2: 4.<\/pre><\/div>\n\n\n\n<p>If you run the script directly, it will produce the desired result, which is <code>4<\/code>. <strong>The issue arises when you try to reuse the <\/strong><code>square<\/code><strong> function in another script<\/strong>.<\/p>\n\n\n\n<p>A new Python script (<code>square.py<\/code>) is created, and the <code>square<\/code> function from the previous script is imported into it.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:4 decode:true \" title=\"square.py\"># square.py\n\n# Main Script Imported as Module\nfrom math_module import square\n\nprint(\"Script Imported as Module.\")\nresult = square(3)\nprint(f\"Square of 3: {result}.\")<\/pre><\/div>\n\n\n\n<p>When you run the above script, the console will display the following output.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Main Script.\nSquare of 2: 4.\nScript Imported as Module.\nSquare of 3: 9.<\/pre><\/div>\n\n\n\n<p>The output shows that the code from the main script (<code>math_module.py<\/code>) is executed first, followed by the code from the currently running script.<\/p>\n\n\n\n<p>You reused the <code>square<\/code> function, but the code inside the main script is executed automatically, which you obviously do not want. This is where you can use the <code>if __name__ == \"__main__\":<\/code> block functionality.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why It Is Used?<\/h3>\n\n\n\n<p>If you add the <code>if __name__ == \"__main__\":<\/code> block after the <code>square<\/code> function code in the main script, the code within the <code>if __name__ == \"__main__\":<\/code> block will not be executed automatically when you import the script in another module.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:8 decode:true \" title=\"math_module.py\"># math_module.py\n\n# Defined a Function\ndef square(num):\n    value = num * num\n    return value\n\nif __name__ == \"__main__\":\n    print(\"Main Script.\")\n    result = square(2)\n    print(f\"Square of 2: {result}.\")<\/pre><\/div>\n\n\n\n<p>The <code>if __name__ == \"__main__\":<\/code> block is added to the main script (<code>math_module.py<\/code>), along with some code. If you import the <code>square<\/code> function from the main script into the second script (<code>square.py<\/code>), the main script&#8217;s code will no longer run automatically.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:4 decode:true \" title=\"square.py\"># square.py\n\n# Main Script Imported as Module\nfrom math_module import square\n\nprint(\"Script Imported as Module.\")\nresult = square(3)\nprint(f\"Square of 3: {result}.\")<\/pre><\/div>\n\n\n\n<p>When you run the above code, you will get the following result.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Script Imported as Module.\nSquare of 3: 9.<\/pre><\/div>\n\n\n\n<p>You may be wondering how a single line of code can restrict the execution of code within the <code>if __name__ == \"__main__\":<\/code> block into another script.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How Did It Happen?<\/h3>\n\n\n\n<p>Curious! How the code in the <code>if __name__ == \"__main__\":<\/code> block was not executed when you ran <code>square.py<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:8 decode:true \" title=\"math_module.py\"># math_module.py\n\n# Defined a Function\ndef square(num):\n    value = num * num\n    return value\n\nprint(f\"Name of the Module: {__name__}.\")\n\n# Remaining code<\/pre><\/div>\n\n\n\n<p>When you run the above code, you will get the following output.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Name of the Module: __main__.<\/pre><\/div>\n\n\n\n<p>When a Python script is run, the <code>__name__<\/code> variable is set to <code>\"__main__\"<\/code>, indicating that the script is being run as the main program.<\/p>\n\n\n\n<p>When a Python script is imported as a module into another script, the <code>__name__<\/code> variable is set to the name of the script\/module.<\/p>\n\n\n\n<p>So, code within the <code>if __name__ == \"__main__\":<\/code> block will only be executed if the script is run directly, not when it is imported as a module. When you print the name of the <code>square.py<\/code>, you will get the following output.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:6,11-12 decode:true \" title=\"square.py\"># square.py\n\n# Main Script Imported as Module\nfrom math_module import square\n\nprint(f\"Name of the Module: {__name__}.\")\n\n# Remaining code\n\n----------\nName of the Module: math_module.\nName of the Module: __main__.<\/pre><\/div>\n\n\n\n<p>You can see that <strong>the name of the main script (<\/strong><code>math_module.py<\/code><strong>) changed which is why the code in the <\/strong><code>if __name__ == \"__main__\":<\/code><strong> block didn&#8217;t get executed when the <\/strong><code>square.py<\/code><strong> script was executed.<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In a nutshell, <code>if __name__ == \"__main__\":<\/code> is like a gatekeeper that ensures that a specific portion of your Python script runs only when you directly execute that script. It keeps things clean, and organized, and helps you create versatile Python modules for your projects.<\/p>\n\n\n\n<p>The <code>if __name__ == \"__main__\":<\/code> can be very handy in larger projects where you have multiple scripts working together. You can import functions and classes from one script into another without running the whole program every time.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/hash-passwords-using-bcrypt-in-python\">Secure user passwords by hashing using bcrypt in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/build-websocket-server-and-client-using-python\">Create a WebSocket server and client in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/threading-module-to-create-threads-in-python\">Create multi-threaded Python programs using a threading module<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/create-and-integrate-mysql-database-with-flask-app\">Create and integrate MySQL database with Flask app using Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/render-images-from-flask\">Upload and display images on the frontend using Flask<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/unit-tests-in-python\">Debug your code using the unittest module in Python<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>You may have seen the if __name__ == &#8216;__main__&#8217;: along with some code written inside this block in Python script. Have you ever wondered what this block is, and why it is used? In this article, you&#8217;ll discover the concept of if __name__ == &#8216;__main__&#8217; block. Understanding if __name__ == &#8216;__main__&#8217;? Well, if __name__ == [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1585,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"","ocean_second_sidebar":"","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"","ocean_custom_header_template":"","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"","ocean_menu_typo_font_family":"","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"on","ocean_gallery_id":[],"footnotes":""},"categories":[2,71],"tags":[12,31],"class_list":["post-1584","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","category-misc","tag-python","tag-python3","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1584","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=1584"}],"version-history":[{"count":2,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1584\/revisions"}],"predecessor-version":[{"id":1588,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1584\/revisions\/1588"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/1585"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=1584"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=1584"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=1584"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}