Understanding if __name__==’__main__’ in Python

On this information, you’ll study the performance and significance of if __name__ == ‘__head__’ in Python.

Have you ever ever browsed a Python codebase with completely different modules?

If that’s the case, you in all probability encountered if __name__ == ‘__main__’ conditionally in a number of modules. Within the subsequent jiffy, we’ll unravel what the above conditional that means means and take a look at an instance the place it may be helpful.

Let’s begin!

What does __name__ imply in Python?

What does __name__ mean in Python?

In Python, a module is one .py operate definition file, a set of expressions to guage, and extra. For instance, if we’ve a file referred to as hello_world.py, we name it the hello_world.py file or the hello_world module.

Once you run a Python module, the Python interpreter units the values ​​for a couple of particular variables earlier than execution: __name__ is one among them. The important thing to understanding the that means __name__ understands how import works in Python.

📁 Obtain the code for this part right here.

Go to the folder example-1. We’ve got the file module1.py. The __name__ variable is within the namespace of the present module.

This module prints a line adopted by the worth of the __name__ variable.

# example-1/module1.py
print("That is module1.")
print(f"The __name__ variable of module 1 is: {__name__}.")

Now, let’s run module1 from the command line.

$ python module1.py

Within the output we see that the __name__ variable is ready to __main__.

That is module1.
The __name__ variable of module 1 is: __main__.

Import modules into Python

Along with working a Python module, generally you wish to use performance from one other Python module inside the present module. Python facilitates this via enter.

Imports assist you to reuse the performance of one other module by importing it into the scope of the present module with out having to rewrite the code.

Import modules into Python

The module2.py file comprises the next. We’ve got imported module1 inside. module2.

# example-1/module2.py

import module1 # module1 is imported

print(f"That is module2")
print(f"The __name__ variable of module2 is: {__name__}.")

We run module2.py and observe the output.

$ python module2.py

Within the output beneath:

  • We see that module1 runs below the hood once we import it indoors module2and the corresponding output is printed.
  • However this time the variable __name__ just isn’t __main__ however module1.
  • As a result of we fled module2 instantly, the __name__ variable akin to the module is now __main__.
Output

That is module1.
The __name__ variable of module 1 is: module1.
That is module2
The __name__ variable of module2 is: __main__.

💡 Core concept:

– If a module is run instantly, the variable __name__ is ready to equals __main__.

– If a module is imported into one other module, the __name__ is ready to the module identify.

Instance of if __name__==’__main__’ in Python

Example of if __name__=='__main__' in Python

Within the part we’ll see a sensible utilization instance of the conditional situation if __name__ == ‘__main__’. We outline a easy operate after which write unit checks to verify if the operate works as anticipated.

📁 Obtain the code and observe alongside.

The code for this part may be discovered within the example-2 folder.

Right here, add.py is a Python file that comprises the definition of the add_ab() operate. The operate add_ab() takes any two numbers and returns their sum.

# example-2/add.py

def add_ab(a,b):
    return a + b
chapter key

We are going to use Pythons unittest module to check the operate add_ab().

Write take a look at instances for a Python operate

Check out the code snippet beneath displaying the contents of the test_add module.

# example-2/test_add.py

import unittest
from add import add_ab

class TestAdd(unittest.TestCase):
    def test_add_23(self):
        self.assertEqual(add_ab(2,3), 5)
    
    def test_add_19(self):
        self.assertEqual(add_ab(1,9), 10)
    
    def test_add_1_minus7(self):
        self.assertEqual(add_ab(1,-7), -6)
    

The above code does the next:

  • Imports the built-in Python chapter key module
  • Imports the operate add_ab() of the add module
  • Defines the take a look at class TestAdd and a set of take a look at instances as strategies inside the take a look at class

To arrange unit checks on your code, you will need to first outline a take a look at class that inherits from unittest.TestCase. All take a look at instances should be specified as strategies inside the class and should start with test_.

Comment: For those who do not identify the strategies as test_<some-descriptive-name>discover that the related checks will not be detected and subsequently not run.

Now let’s strive the test_add module of the terminal.

$ python test_add.py

You will note that there isn’t a output and not one of the checks have been run.

Why is that this the case?🤔

It is because to run the unit checks, it’s essential run unittest as the principle module when working test_add.pyutilizing the command beneath.

$ python -m unittest test_add.py

When working the above verbose command, we see that every one three checks have run efficiently.

Output
...
----------------------------------------------------------------------
Ran 3 checks in 0.000s

OK

Nonetheless, it’s helpful to run the checks when this module test_add is run, sure? Let’s discover ways to do that within the subsequent part.

If __name__ == Use ‘__main__’ to run unittest as the principle module

Run unit test as the main module

If you wish to run all unit checks when the module is run instantly, you should use the conditional.

# example-2/test_add.py

import unittest
from add import add_ab

class TestAdd(unittest.TestCase):
    def test_add_23(self):
        self.assertEqual(add_ab(2,3), 5)
    
    def test_add_19(self):
        self.assertEqual(add_ab(1,9), 10)
    
    def test_add_1_minus7(self):
        self.assertEqual(add_ab(1,-7), -6)

# Run unittest as the principle module
if __name__ == '__main__':
        unittest.essential()

The conditional within the code snippet above tells the Python interpreter: If this module is executed straight, then execute the code in it. unittest.essential().

You possibly can the test_add module after including the above two traces of code.

$ python test_add.py

▶️ Operating the add checks module straight will now run all three checks we outlined.

Output
...
----------------------------------------------------------------------
Ran 3 checks in 0.000s

OK

The above OK output signifies that every one checks have run efficiently. The three dots… point out that three checks have been carried out and all handed.

Now let’s change the anticipated return worth test_add_1_minus7 to eight. For the reason that operate returns – 6 on this case, there must be one take a look at error.

def test_add_1_minus7(self):
        self.assertEqual(add_ab(1,-7), 8)

As proven within the output beneath, we get .F.out of three checks, one of many three checks (the second take a look at) failed, and within the traceback we get one AssertionError stating – 6 != 8.

Output
.F.
======================================================================
FAIL: test_add_1_minus7 (__main__.TestAdd)
----------------------------------------------------------------------
Traceback (most up-to-date name final):
  File "test_add.py", line 12, in test_add_1_minus7
    self.assertEqual(add_ab(1,-7), 8)
AssertionError: -6 != 8

----------------------------------------------------------------------
Ran 3 checks in 0.021s

FAILED (failures=1)

An necessary factor to notice is that the checks not essentially are executed in the identical order they’re specified within the take a look at class. Within the instance above test_add_1_minus7 is outlined because the third technique within the take a look at class, however the corresponding take a look at is run second.

Sum up

I hope this tutorial helped you perceive how the if __name__ == ‘__main__’ conditional works in Python.

This is a fast abstract of the principle takeaways:

  • The Python interpreter units the __name__ variable earlier than working the Python script.
  • Once you run a module straight, the worth of the __name__ is __main__.
  • Once you import a module into one other Python script, the worth of the __name__ is the module identify.
  • You should use if __name__ == ‘__head__’ to manage execution and which elements of the module are executed throughout direct and imported runs, respectively.

Then try this in-depth information to Python units. Have enjoyable studying! 🎉

Leave a Comment

porno izle altyazılı porno porno