Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.

Defining Main Functions in Python: Summary

Congratulations! You now know how to create Python main() functions.

Here’s what you covered:

  • Knowing the value of the __name__ variable is important to write code that serves the dual purpose of executable script and importable module.

  • __name__ takes on different values depending on how you executed your Python file. __name__ will be equal to:

    • "__main__" when the file is executed from the command line or with python -m (to execute a package’s __main__.py file)
    • The name of the module, if the module is being imported
  • Python programmers have developed a set of best practices to use when you want to develop reusable code.

Now you’re ready to go write some awesome Python main() function code!

Download

Sample Code (.zip)

2.2 KB

Download

Course Slides (.pdf)

277.0 KB

Comments & Discussion

Gregory Klassen on March 10, 2020

What does it mean to … ” or with python -m (to execute a package’s main.py file)

Eribertt on March 12, 2020

The switch m means module, so from the command line supply python with the module name to call it.

Lando on March 12, 2020

Is there a design pattern/best practice/examples to convert a script file that uses argparse at the top level with global variables, into a module-based format with independently callable functions?

I’ve inherited a python script like that, but need to also use it as a module.

I’m trying the approach of moving the argparse bits into the main() function to preserve the ability to run it as a script, and for module use I’ve created individual function wrappers to take arguments, and the function wrappers then set the global variables and then call the original function (so I don’t have to touch the original code that much).

Anonymous on March 14, 2020

Very Good

Pygator on March 14, 2020

Good distinction between file, module for importing, and script for command line execution of the files .py extension in general. Made name usage more clear.

markthiele on March 16, 2020

Thanks, very nice.

horacionesman on March 22, 2020

very useful, thanks!

malshishani on March 22, 2020

Thank you a lot, really good :).

pshapard on March 27, 2020

Completed my first course. I new about the main() and name. I’m using this during the lockdown due to the corona virus to brush up on what I already know about python and learn new areas of python.

Become a Member to join the conversation.