Fairly new to the world of Python and coming from MATLAB I was always taught to use a run()
function to execute a script.
However when working with multiple .py
files in Python, I've noticed it's common (required?) to use __main__.py
and subsequently a main()
function in each script.
I read through the PEP8 Style Guide and the Google Style Guide and it seems having a main()
function in every script seems to be common convention but...
Am I incorrect (or in bad style) for using run()
? What is your preferred naming convention?
However when working with multiple .py files in Python, I've noticed it's common (required?) to use main.py and subsequently a main() function in each script.
No, it's not required to include __main__.py
file in your Python package. Put simply, __main__.py
is an convenient entry point hook that allows you to name what code should be run if you were to run your module with Python. For example, if I had a package (folder) named foo
with a __main__.py
file:
foo
|
+--- __main__.py
|
+--- foo.py
I could then directly run the package from the command line:
$ python foo
Python would then execute the __main__.py
file in foo
. As you can see, this allows for a convenient way for someone to execute the code in your package.
Am I incorrect (or in bad style) for using run()? What is your preferred naming convention?
You have the freedom to name the main function that executes your code whatever you choose, including run
. The reason people commonly call it main
because in other languages, a function named main must be called to execute a program. It's the entry point the OS uses to execute your program.