Search code examples
python-3.xprogram-entry-point

How can I use different name for a function other than main in python?


I want to use a function name other than main as a main function. Is it possible to do it? This sounds like a basic question but since I'm new to python, I wanted to make sure that I am going correctly.

file1.py

def func1():
"""some code"""

def func2():
"""Some code"""

def main(arg1,arg2):
    func1()
    func2()

if __name__=="__main__":
    main(arg1,arg2)

I expect to use a different name for "main()" method here.


Solution

  • You can just do it:

    def not_main(arg1, arg2):
        func1()
        func2()
    
    if __name__ == "__main__":
        not_main(arg1, arg2)
    

    The if __name__ == "__main__": syntax is, unfortunately, unavoidable - what it does is it checks if the current file is being run as a script (as opposed to as an imported module). The convention is to have a function main() that holds the "main business logic" of your application, and have it be called inside the if __name__ == "__main__": block, but there are plenty of reasons not to do that, and it's not at all required.