tadm123 tadm123 - 16 days ago 10
Python Question

Importing modules that have all its functions inside a main() function

I read the answer given below:

Why use def main()?

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

Answer

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