The difference | Sololearn: Learn to code for FREE!

+5

The difference

Take for example: test = [x for x in range(1, 5)] def addition(x): print(sum(x)) If i needed the function, I'll just do: addition(test) I see senior/experienced programmers use this sometimes and often: if __name__ == '__main__': addition(test) What is the difference? Cos they both seem to do the same thing. Please enlighten me.

5/7/2020 8:47:29 PM

Tomiwa Joseph

5 Answers

New Answer

+6

When you spread up your code among several modules, only the one you start directly will have the name '__main__'. All other modules, which you import, will go by their module names. This allows you to write test code into your function modules that you can just leave there. If the program runs normally, it'll just be ignored. But if you change something in a module and want to run the tests, you can start the module directly.

+4

__name__ is a special variable. Whenever you run a python script, the __name__ variable will get a specific value. This happens in background, so you will not notice it... Now when you run the script stand alone, as your main script so to say, it will get the value "__main__".. But when you import it into another script (which is in this case the main), it will get the module name (e.g. myScript for myScript.py). Now you see, the <If __name__ == '__main__'> block will only be executed, when you run the script as main. It will not be executed, when the script is imported...

+2

I totally understand now. Thanks HonFu G B

+1

Thanks guys. So, the imported modules are just called while the stand alone main script gets called with the "if __name__ == __main__" block. Yes?

0

Not exactly. It just functions like a regular if block. When you import a module, the whole code will be executed, just like when you start a module directly. So module a could be empty, module b could contain the line print('Hello'). Then this code, without further ado... import b ... would print 'Hello'. Now if module b looks like this: if __name__ == '__main__': print('Hello') ... running module a will not lead to the output, because module b is imported and the test for its name returns False.