You can often see this (variation a):
def main():
do_something()
do_sth_else()
if __name__ == '__main__':
main()
And I am now wondering why not this (variation b):
if __name__ == '__main__':
do_something()
do_sth_else()
Or at least this (variation c):
if __name__ == '__main__':
def main():
do_something()
do_sth_else()
main()
Of course the function calls inside main() might not be function calls, they just represent anything you might want to do in your main() function.
So why do people prefer variation a over the others? Is it just style/feeling or are there some real reasons? If possible, please also link sources.
Why limit your main() function to command line usage only?
By defining a main() function at module scope, you can now wrap your script and alter how it is called. Perhaps you want to set default arguments in sys.argv, perhaps you want to reuse the code in another script.
This is because there are two ways of using Python scripts. One from the command line and another when importing it from another script. When you run it from command line, you want to run main() function and when you import it you may not want to run main() function until you need it ( you just want to import main() ).
Related
It is said to be a good practice to write the following block of code in your python modules:
if __name__ == '__main__':
# execute only if run as a script
main()
This prevents executing statements when you want to import this module into another program.
However, the curious thing over here is that main() function. We also need to put our code into an actual main method as follows:
def main()
# All code goes here
print("Inside main")
I feel that this is a roundabout way. Are there any benefits to creating a separate main() function and then calling it inside the if-clause?
Instead what is the harm in writing the code directly inside the if-clause?
if __name__ == '__main__':
# All code goes here
print("Inside main")
However, the curious thing over here is that main() function. We also need to put our code into an actual main method as follows:
Well, you dont need to do so. Actually if all you want is a plain script (something that's not going to be used as a module), you don't even "need" any function at all, you could as well put all your code directly at the top-level. BUT this will not make for clean, maintainable, testable code.
I feel that this is a roundabout way. Are there any benefits to creating a separate main() function and then calling it inside the if-clause
Quite simply the same benefits as you get from using functions (and modules and classes) to organize your code: clean, readable, testable, maintainable code. Just ask yourself how you are going to test your main function if you don't have a main function ?
Why is it standard in Python to have the main() function and the if __name__ == '__main__' check at the end of the block of code? It also seems standard for the abstraction of the functions to follow the same pattern upwards. What I mean is that the definition of the function to be executed by main() is above the main() and the definition of the functions inside that are above and so on..
That seems odd because when one opens the module to read the code, it ends up starting with low-level code and moves up to higher level functions. Isn't it hard to grasp what the module is doing that way?
Why not do the alternative? Have the if __name__ check at the top followed by the main() function, and so on. This way, one quickly glances at what the main() function does and understands what the code is about.
You can't call main() before it is defined. And main cannot call other functions before they are defined.
Example 1:
if __name__=='__main__':
main()
def main():
print("Hello")
This will error because main hasn't been defined yet at the point where you try and execute it.
Example 2:
def main():
hello()
if __name__=='__main__':
main()
def hello():
print("Hello")
This will error because main() is executed and tries to call hello before it is defined.
The if __name__=='__main__': which contains the call to main() works best at the end of the file so that everything that it needs has been defined before it is reached.
Where you put the main definition itself is more flexible, but putting it at the end (just before the if __name__=='__main__': block that calls it) makes as much sense as anywhere else.
The purpose of an if __name__ == '__main__': guard is to prevent a module from having side-effects when it's imported.
The fact that it is a module rather than a script implies that it will normally be used by other code importing the definitions from it, not executed directly. So given that, it makes sense that the functions, classes and constants appear first in the source code, since those are what users of the module will be importing (and hence, what they might want to see the source of).
So even if the code guarded by if __name__ == '__main__': doesn't rely on the definitions in the module already having been evaluated (which would be unusual), this part of the code is usually the least important to the users of the module, so it doesn't belong at the start of the file.
This question already has answers here:
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
(5 answers)
Closed 6 years ago.
I am writing a simple Python program with some functions, one of which is a main() function executes the other functions. However when I run the code below there is no output. Can someone tell me if they see an error in the structure?
def print1():
print("this is also a function")
def print2():
print("this is a function")
def main():
print1()
print2()
You need to call main(). Right now it is just a definition. What use is an entry in a dictionary if nobody uses the word?
def print1():
print("this is also a function")
def print2():
print("this is a function")
def main():
print1()
print2()
main()
It is common in Python programs to do things differently depending on if the file is being imported or run. When a file is executed, the __name__ variable is set either to '__main__' or the name of the file. It is set to '__main__' if the file is being executed as a python script, and it is set to the name of the file if it is being imported. You can use this information so that you don't actually run anything if it is just being imported instead of being run as a python script:
if __name__ == '__main__':
main()
That way, you can import the module, and use the functions without main() being called. If it is run as a python script, however, main() will be called.
Add this to the bottom of your code.
if __name__ == "__main__":
main()
See https://docs.python.org/2/library/main.html
Main needs to be called explicitly. You can do it without the if statement, but this allows your code to be either a module or a main program. If it is imported as a module, main() won't be called. If it is the main program then it will be called.
You are thinking like a C programmer. In this case python acts more like a shell script. Anything not in a function or class definition will be executed.
You need to call main() in order for it to run.
I believe what you mean to be doing is
def print1():
print("this is also a function")
def print2():
print("this is a function")
if __name__ == '__main__':
print1()
print2()
Call this script something.py and then run python something.py from your command line.
I wrote a function that makes a screenshot and checks if it's different than the old one. The example code is below. However, I wonder about pythons best practice to set the variables oldimage and image. Especially oldimage needs to be set before main() can start the first time. Do I use global variables?
def main():
image=screenGrab()
if equal(image,oldimage):
pass
else:
dosomething()
oldimage=image
while True:
main()
Using global variables is almost never the correct solution. It usually ends up causing more problems than solutions. Continuing from #MartijnPieters, I would organize your code as follows:
def main():
oldimage = loadLastImage()
while True:
image=screenGrab()
if not equal(image,oldimage):
dosomething()
saveLastImage(image) # this is the opposite of loadLastImage()
oldimage=image
# this is the more accepted way of running main
# because it still allows your code to be loaded as module
if __name__ == "__main__":
main()
I go into File-properties-edit-arguments type a string. When run program I get no output.
def print(n):
print n
Be sure you're calling the method from somewhere, typically a main() or test() function in the Python file. Also, avoid using print, since that masks the actual statement/function. (In Python 2.x, this won't even run - you have to name it something other than print.)
def main():
print(raw_input("Will print something "))
if __name__ == '__main__':
main()