[Tut] What Does “if __name__ == ‘__main__’” Do in Python? - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] What Does “if __name__ == ‘__main__’” Do in Python? (/thread-95984.html) |
[Tut] What Does “if __name__ == ‘__main__’” Do in Python? - xSicKxBot - 07-01-2020 What Does “if __name__ == ‘__main__’” Do in Python? <div><p>Today, let’s discuss something that’s all over the place in many code bases: what does <strong><em><code>if __name__ == '__main__'</code></em></strong> do in Python?</p> <p>If you are learning Python programming step by step, you would have bumped into the above piece of code snippet somewhere. Even if you have not, I am sure you will soon come across it, and this might feel like a jerk in your so far smooth journey of learning Python programming. I have been there. I was going through a book on Python programming when I first saw this piece of code, and I thought—wait a minute, did I miss anything on my way up to here? Then I went back, revising the last few pages to figure out what I missed, and this loop went on for a while before I finally sat down to face the demon, and honestly, I smiled when I figured it out, it is that simple. Maybe, we learn this way. We go back and forth, keep jumping, and then one day, the magic happens. The only thing that works is not giving up. </p> <p>Today I will try to make this understanding simple for you in a way that will hopefully bring a smile to your face if you have been in the loop of getting a hint of what it is and then keep forgetting.</p> <p>To understand what is <em><code>if __name__ == __main__</code></em> used for we will dive into some code examples first to understand what <em><code>__name__</code></em> and <em><code>__main__</code></em> are. Then we will cement the learning through another example. So be patient and go through the article carefully. The code snippets may look a little confusing but wait until we explain and see what is happening exactly.</p> <p>What are <code>__name__</code> and <code>__main__</code>?</p> <p>Let us start with <em><code>__name__</code></em>. Simply put, <em><code>__name__</code></em> is a special variable that is built-in in Python. </p> <p>In Python, we can run code as a source file or, in other words, a python code that runs on its own (read – not imported from some separate Python source file). This sentence may be confusing at the moment, but let us explore this further.</p> <p>Look at the code snippet below. It is a simple python file with just one line:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(f" First Module's Name : {__name__}")</pre> <p>Simply put, we are asking Python to print the value that <em><code>__name__</code></em> variable has at this moment. Notice there is no import statement or even any other line of code above it. </p> <p><img src="https://lh6.googleusercontent.com/ixWY9y_OT8yQeaZlsf4iF5W_aX1v7XYOyDE9T3Qiaqc9EaTMdVPJO6X1GTh9a8KtRiYUil4_hWc8tQnlDPYHkyJe-QXiq9JK5IO1_llF3oV34H1UJbKOZEjIetlp3D4CBQFdekR3" width="500" height="175"></p> <p><strong> Figure 1</strong></p> <p>Check the output in Figure 2 below. We run the above lines of code and find the output </p> <p><strong><em>First Module’s Name : <code>__main__</code></em></strong></p> <p><img src="https://lh4.googleusercontent.com/lN0eXeqZ_4mqr7x32m2fn09S0K3Hqz6tZ7TMZVVp0kT0LoKGWuU5xKcof002DXSA1_VlC1frmYhHB65n2VHV4XJTO5MBH51zIBS2jV7ULi_KgO19bXGx9AA30t-53r1dGJnZxD_b" width="624" height="136"></p> <p><strong> Figure 2</strong></p> <p>We import <code>module1.py</code> into <code>module2.py</code> and ask Python to return the second module’s name (second because this is the second python code we are running) stored in<code> <em>__name__</em></code><em> </em>variable again.</p> <p><img src="https://lh6.googleusercontent.com/FDrm4f07_lWBC3GBgUhZhQFSqPzYKBzDs_V3TI5X1OrpEj0ZdZ49rZRGsmslIbmDkX4Lq5H4fj-5Xrpk2_3x7yaRHAkSqAWkjbjSZo-BaxX0UBlaek3qCHazEENu2ugbbzlsFOy5" width="542" height="144"></p> <p><strong> Figure 3</strong></p> <p>Interestingly, in Figure 5 below, we have the output </p> <p><strong><em>First Module’s Name : module1</em></strong></p> <p><strong><em>Second Module’s Name : __main__</em></strong></p> <p><img src="https://lh4.googleusercontent.com/UOVArPdiVS-NiiG_biktjplo2fzh-Ls8xP1yvmn05aDwrC8hgzAJzmhtlqdDClEkfLdjHeqrF1CxQOViCbcIQDrWRJPeUUgksh899pCe8iZqJdKOqMavmLUwxXqktm7eOKVe0xGH" width="624" height="121"></p> <p><strong> Figure 4</strong></p> <p>The above information summarised simply can be explained as follows. Python starts executing the first line of code found in a Python file, but before it runs anything to show the output, Python defines some special variables. <em>__name__</em> is one such variable. When the source file is executed on its own i.e, not being imported from some other source code, the<em> __name__ </em>variable is set to value <em>__main__</em>, and hence the output we got in Figure 3 was <em>First Module’s Name : __main__</em>. If you import the file from some other module (as in the code snippet from Figure 4), the value of <em>__name__</em> variable is set to the name of the module it is imported from. Hence the output in Figure 5.</p> <p>Now let us look at the sequence of execution.</p> <ol> <li>module1.py in Figure 1 is executed,</li> <li>Variable <em>__name__</em> is set to the value<em> __main__</em></li> <li><em>__main__</em> module is executed, and the output is <em>First Module’s Name : __main__</em> </li> <li>Module2.py in Figure 4 is executed,</li> <li>Variable<em> __name__</em> is set to the value <em>module1</em></li> <li><em>module1</em> is the block of code in module1.py which is executed, and the output is <em>First Module’s Name : module1 </em></li> <li>Next, we move on to line 3 in module2.py, the name value is reset to <em>__main__</em>, because this is a fresh piece of code in module2.py, and the output is <em>Second Module’s Name : __main__</em></li> </ol> <p>Using if __name__ == ‘__main__’</p> <p>But let’s think only concerning the code in module2.py. In the real world, with module2.py I would not like to print the output from module1.py rather only import some functionality and get output for the lines of code written in module2.py i.e. <em>Second Module’s Name : __main__</em></p> <p>But how can we do it? There has to be a way because this seems more logical that way. Refer to the code snippet below in Figure 6.</p> <p><img src="https://lh5.googleusercontent.com/x3Io0KK_w7stlPNBv-boKOk0FrjsRfPZjbRCcFy7vGR_wx8NxJS1OYTMdsZPHHPmOBz2A5wy42EO-uv9_3xp5T56w1DVsYkwtKJM7bpX_hpFEVqFNODCjnfYnCjCr46sRPzvFe8y" width="576" height="195"></p> <p><strong> Figure 5</strong></p> <p>So, we will define a function main(), and put the print statement from module1.py inside the main function. Now we use this small trick of using the statement <em>if __name__ == ‘__main__’</em> and put the main function inside this if statement. Now let’s look at the execution sequence of our program.</p> <ol> <li>We have a main() function where we ask to print the name of the first module stored in <em>the __name__</em> variable. From the above example, we know the value stored in the <em>__name__</em> variable is __main__</li> <li>In line 7, we say if the value in <em>__name__</em> variable is equal to <em>__main__</em>, only then go ahead and execute the <em>main() function</em>.</li> <li>Now running the modified module1.py, we can see the output as <em>First Module’s Name : __main__</em> as expected. Refer to the first output in Figure 7 </li> <li>Now when we run module2.py, we get the output as <em>Second Module’s Name : __main__</em></li> </ol> <p>Notice how the output for module2.py has changed now. Although we have imported module1 in our module2.py program, the program in module1.py doesn’t run. Why? Because the value stored in the <em>__name__</em> variable at this moment is module1 and not <em>__main__</em>. So, using a main() function and<em> if __name__ == ‘__main__’ </em>has put restrictions on execution of lines of code in module1.py as it would only execute module1.py only if <em>__name__ == ‘__main__’</em></p> <p><img src="https://lh4.googleusercontent.com/jTHhckxRAMrjKxsfSHO-XPtSHW2CuHxGSsa4Y5BBYzqyUKDl7wnSx8kskggeLIKnmtp0qgSjCQEwlq1zskVomDaPWytxaf7rw6qY_iDtsBt9cWreOiFQm0WnMCviBX98Pui1ujWO" width="624" height="135"></p> <p><strong> Figure 6</strong></p> <p>Putting it all into a real-world example</p> <p>We now take a more generic example, which would make more sense of all we have discussed above.</p> <ul> <li>Have a look at the below code snippet from cubes.py in Figure 8. In line 1 and line 2, we have a function cube(), which takes num as an argument. The function cubes(num) returns the cube of a given number.</li> <li>On line 4, we use a for loop which iterates over a list of numbers from 0 to 9.</li> <li>On line 5, we use the cubes(num) function with i as input to display the cube, as shown in figure 9. Simple enough.</li> </ul> <p><img src="https://lh4.googleusercontent.com/TJOYJs0u31mM170mt0bfpn6MgdOyk9bFggO2E9X6hu-Ldszo7ObG0AhjMQxt9TagvCkt8LMD8QRZANjTP-5OslxLF1eaPtWWPxBKeSzWxLukj2nnuLH3cK_CbI9I-_kQdLdNnSig" width="570" height="155"></p> <p><strong> Figure 7</strong></p> <p><img src="https://lh6.googleusercontent.com/Sdn17AJmX7ITEwRRGWfTr7GGLzcuGL8z2RU0XVKhrOfjj8Qk4KpUgtD0SoOSNPVuoBIuyu3mX7WJZ9ic2BmjkmQtW7ySiYv59U9Gcsnr8bNG-xlToyChxmeJAWaU3jTaeIoucUC5" width="624" height="252"></p> <p><strong> Figure 8</strong></p> <p>In the code snippet from modules.py below in Figure 10, we import cube(num) function from cubes.py and try to print cube of 10 in line 3. Logically, we are trying to use the function cube(num), which returns a cube of any given input number.</p> <p><img src="https://lh4.googleusercontent.com/1PbrMx0TTjtcbhZARySffFG_hs1JVBp3aemQ2NXC2BXYsnf3JuzZxTTTK24qX9pv8jUd6LS7VcF34pTPmJM1K9zUp55QS0hGMEeYh7Iz3BZLnDomxP5gQ3oCVynhXi2S7Fr8Dx4e" width="423" height="130"></p> <p><strong> Figure 9</strong></p> <p>However, look at the output below. We have the output of both the programs cubes.py and modules.py. This is not what we intended or wanted to do. </p> <p><img src="https://lh4.googleusercontent.com/VwFC1f6oeN348PQVV4XSk-qP5lvjj4_Z1uGTi_Gb82_RC59pceAY0dwIH_n-MLkc5T7VWuKEQZCpe4Js_JIs4iP-tJFkNA7g4u7fKR7GVh7uAYY4dLpR7mIXUaTZnmug0OKdkoqM" width="624" height="256"></p> <p><strong> Figure 10</strong></p> <p>Remember the explanation from above where we used <em>if __name__ == ‘__main__’</em> to limit the execution of code from modules1.py. Let us try and implement the same idea and see if that works here.</p> <p>In the code snippet from cubesModified.py in Figure 11, we put the for loop and the print statement from cubes.py in the main() function. And again, we use the statement <em>if __name__ == ‘__main__’</em> to execute code from cubesModified.py only when the value of __name__ variable equals to <em>__main__.</em></p> <p><img src="https://lh3.googleusercontent.com/cuuWr6W-MXEGx-K_YYy6B7c5FLzJ0_mMEvkGkHX5HTUD7ShPA3wXuEh_Ussr0uCjub-BdvmOn_sJI3RLhLUqh65z-BL9sUDE1Yqe26Ptysca3UjrCe8VUOVkbtokdrLwicARm5Wn" width="624" height="331"></p> <p><strong> Figure 11</strong></p> <p>We run cubesModified.py and get the output as below and per our expectation.</p> <p><img src="https://lh5.googleusercontent.com/LyD3_e4XeP7mz2uEAvv4pyb0S5E2ub6dAD2TqmIDbYlfkjfBBWb5K1Q0-rvcpnrPiW1PX-Y0NlKIq8xBbCpdxqxSI68VVERaruTwQwYvU9x_pEOutos7wu4vjLYBtH28Q2EpRTBN" width="624" height="253"></p> <p><strong> Figure 12</strong></p> <p>However, now when we run modulesModified.py where we import cube(num) function from cubesModified.py, it only executes the code from our modulesModified.py as shown in Figure 15, and the output is 1000 because the value stored in the <em>__name__</em> variable in cubesModified and not <em>__main__.</em></p> <p><img src="https://lh3.googleusercontent.com/ybVD8QsySwt8XIMvSOqE3Tnq0z1LKRIyGDAXKt16z5UFXFm1SZQi_Skwmvgy5uQAFWoYEsYlbtuNL4t037bDuSPqmJchK3-3Dx0rkypfLKS3S19OV_9ry7nn8rENK-2U2Bq6nLbV" width="458" height="130"></p> <p><strong> Figure 13</strong></p> <p><img src="https://lh3.googleusercontent.com/vOoB4MSBk8XfxAKKyszUkeIoLitG5BcKz1GJH-PnK9KSt6GzmARGBeQ3fIMSk756acAObrUYWv__YCde0Rvc5Dlk1o31m3B2TY9u7t0qFsRTZ1m-M9IEMbMWWkafYkdvnnZucvv6" width="624" height="93"></p> <p><strong> Figure 14</strong></p> <p>I hope this explanation helps you with a better understanding of what does <em>if __name__ == ‘__main__’</em>. Go ahead and play around with the code in the code editor and cement your understanding. Best of Luck!!</p> <h2>Author</h2> <p>This article is contributed by Finxter <strong>Abhigyan Ojha</strong>. <a href="https://www.upwork.com/o/profiles/users/~01c5bce36c9a7b65d4/" target="_blank" rel="noreferrer noopener">You can find his Upwork profile here.</a></p> </div> https://www.sickgaming.net/blog/2020/06/30/what-does-if-__name__-__main__-do-in-python/ |