Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

7.3 Top-level code

Learning objectives

By the end of this section you should be able to

  • Identify code that will run as a side effect of importing.
  • Explain the purpose of if __name__ == "__main__".

Side effects

Modules define functions and constants to be used in other programs. When importing a module, all code in the module is run from top to bottom. If a module is not designed carefully, unintended code might run as a side effect. The unintended code is generally at the top level, outside of function definitions.

Using __name__

Python modules often include the statement if __name__ == "__main__" to prevent side effects. This statement is true when the module is run as a program and false when the module is imported.