1

In the module 'test_name_function.py' as I am importing 'get_formatted_name' why is the if block getting executed

# name_function.py
def get_formatted_name(first,last):
    """Generate a neatly formatted name"""

    full_name = f"{first} {last}"
    return full_name.title()

# test_name_function.py
import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):
    """Test for name_function.py"""

    def test_first_last_name(self):
        """DO names like 'Rajat Sharma' work"""
        formatted_name= get_formatted_name('rajat','sharma')
        self.assertEqual(formatted_name,'Rajat Sharma')

if __name__ == '__main__':
    unittest.main()
  • 2
    Because that `if` block is in the main module that you executed, not in the module that is being imported. I don't understand why you expect anything different. You might as well ask why `import unittest` doesn't stop the `if` block. – Karl Knechtel Aug 17 '21 at 19:21
  • @KarlKnechtel- Sorry, but I am beginner and having hard time figuring out, when does importing a file or function would trigger the 'if __name__' block and when not. Thanks – Praveen Paliwal Aug 17 '21 at 19:39
  • The expectation seems a little unclear here, but the question has a clear and concise example, and it asks a question many new users have about a pretty obtuse bit of boilerplate. Users who need this question wouldn't be helped by the two page explanation of the precise background mechanics of the expression. This shouldn't be closed. – Dan Monego Aug 17 '21 at 19:41
  • See https://www.youtube.com/watch?v=g_wlZ9IhbTs or https://www.youtube.com/watch?v=sugvnHA7ElY. – jarmod Aug 17 '21 at 19:43
  • 2
    @PraveenPaliwal the if statement is always executed. The check ensures that the main function or unit test suite is only executed if it's the entry point from python. So `python test_name_function.py` would cause the suite to execute, but if you import from somewhere else, it won't execute. – Dan Monego Aug 17 '21 at 19:44
  • 2
    @DanMonego You can't just look at the first answer and conclude it shouldn't be closed. The duplicate has **38** answers, all in varying quality and length. I don't see how adding more answers would be beneficial. – Ted Klein Bergman Aug 17 '21 at 20:04
  • Thanks @DanMonego, I got it now. – Praveen Paliwal Aug 17 '21 at 20:12
  • 2
    There's nothing special about the `if` statement. All you need to know is how the variable `__name__` is set by the interpreter. The purpose of the `if` statement flows pretty naturally from that. – chepner Aug 17 '21 at 20:15
  • 1
    Importing a module in the file where you have `if __name__ == '__main__'` has nothing to do with it. The question is whether *this* file is the one you are running, or whether it was imported from somewhere *else*. – Karl Knechtel Aug 17 '21 at 21:03
  • Thanks @KarlKnechtel – Praveen Paliwal Aug 18 '21 at 10:03

0 Answers0