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()
?