Introduction
Visual studio code primer
Modules and packages
Virtual environments and package management
Intermediate Python Concepts
Built-in libraries for daily use

Runnable Python modules

We can create something that is often called a runnable module. Such a module can be both used as a script, and used for importing from them. Inside a module, you can detect if the file is used as a module or a script. In this topic, you’ll learn how to do this.

The If __name__ == '__main__' check

You might have seen it before, and you might have wondered what it does. Why do Python programmers include this check inside their script so often? It has everything to do with modules and using modules as scripts.

When we import a module, its name (stored in the variable __name__) is equal to the module name. When a script is executed, its name is always set to the string __main__. Hence, if we check for this name, we can detect if we are running as a script or if we’re being included somewhere as a module.

By only executing code when running in ‘scripting mode’, when the name is __main__, we can effectively create files that can both act as a script and as a module that can be imported.

I created a simple module that does this check in the following code crumb. Because we don’t import this file but run it directly, the function is executed and we see something printed to our screen. If you would import this module, however, the function would not be called:

A runnable module that checks if it is used as a module or a script