2

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?

  • 1
    The tradition to call the main function `main` comes from the C/Java/C++/C# world where the main function _must_ be called `main`. – DYZ Jan 25 '18 at 00:09
  • 2
    You can name your function whatever you like. There's really no hard set rule. As @DYZ said, people commonly call it main because in other languages, a function named `main` must be called to execute a program. – Christian Dean Jan 25 '18 at 00:10

2 Answers2

1

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.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
0

You can use execfile(filename) in Python shell.

The detailed solution to your problem can be found here.

P.S. There is no need to name your function main() or so. Choose anything you like that is not reserved or built-in.