Reputation: 8787
I read the answer given below:
It seems it's better practice(?) to put all the code inside a main()
function when creating modules to avoid executing it when imported.
But at the same time, when I put all my functions inside main()
and I want to import it to another program, how would I call all these functions?
It seems counterproductive to do that but obviously I'm understanding it wrong, so I appreciate any help I could get.
EDIT: So let me know if I understood it, we don't put any actual functions inside main(), they are separate functions. The only thing that will go inside it its the __main__
portion? For example:
Program test.py
:
def my_function():
print('Hello')
def my_function2(num):
return num*num
print('Hi')
Modified test.py
def my_function():
print('Hello')
def my_function2(num):
return num*num
def main(): #so it doesn't execute when imported
print('Hi')
Is this an accurate way of how you would use the main()
?
Upvotes: 1
Views: 680
Reputation: 41158
main()
typically calls your other functions but does not contain them. Your other functions will lie in the body of the script above main()
and can be called in the standard way.
So your test.py
example could look like this:
def my_function():
print('Hello')
def my_function2(num):
return num*num
def main():
my_function()
my_function2(5)
if __name__ == "__main__": # if module not imported
main()
Upvotes: 5
Reputation: 31
You call the functions you want to execute within the block below. The functions are assumed to be already defined at the top of your module
if __name__=="__main__":
call your functions you want to execute
Upvotes: 1