Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

Why does importing a Python module run its example code?

Quick answer

Importing a module executes its statements. So an example call written at the top level can run as soon as another file imports that module. Keep reusable definitions at module level, put the example or command-line steps in a main() function, and call main() only under if __name__ == '__main__':. That guard distinguishes running the file as the program from importing it. [S1]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

Why does importing my Python file print the example output? I expected the example to run only when I start that file.

Geez

Because Python executes a module’s statements as it loads the module. When another file imports yours, top-level statements run too—including a demonstration call such as print(greet("Sam")). [S1]

For example, this file named greetings.py has a top-level example call:

def greet(name):
    return f"Hello, {name}!"

print(greet("Sam"))

Importing it to use greet also prints Hello, Sam!. The function definition is useful reusable code; the final line is an action you probably want to control. Move that action behind the standard __main__ guard.

Follow-up question

What should the before-and-after version look like if I want to keep a runnable example?

Geez

Keep the function available at module level, put the example steps in main(), and call that function only when the file is run as the top-level program:

def greet(name):
    return f"Hello, {name}!"


def main():
    print(greet("Sam"))


if __name__ == "__main__":
    main()

Python sets __name__ to the module’s name when it is imported, and to '__main__' when the file is run as the program. The condition therefore allows the example to run in the latter case without running it on import. [S1]

A typical layout is: imports, reusable constants and function or class definitions, then main(), then the guard at the bottom. Put only the run-the-example or command-line steps in main(); callers can import and use greet without triggering those steps.

Follow-up question

How can I tell whether I fixed it when a second file imports the function?

Geez

Make a small caller that imports the function and uses it, without calling main():

# try_import.py
from greetings import greet

print(greet("Lee"))

Run try_import.py. With the guarded greetings.py, the caller should print Hello, Lee!; the Sam demonstration should not run during the import. This is a focused check of the behavior you intended. It does not establish that every possible use of the module is correct; it checks that this import does not trigger the example output.

If importing still performs an action you did not expect, look for other top-level calls or statements in the imported file and in modules it imports. Definitions belong at module level, but actions intended only for the runnable example should be reached through the guarded main() call.

Follow-up question

Does the guard mean I should put all my code inside main()? What’s a simple pattern I can reuse?

Geez

No. Keep reusable definitions outside main() so other modules can import them. Use main() for the sequence that should happen when someone runs this file, and protect its call with the guard. [S1]

Reusable pattern:

# my_module.py

# Reusable definitions

def do_example():
    return "example result"


def main():
    result = do_example()
    print(result)


if __name__ == "__main__":
    main()

Replace do_example() and the print with your own example steps. For a command-line script, main() is also a natural place to organize that script’s actions. The guard controls whether main() is called; it does not automatically prevent other top-level statements from running during import, so keep unintended actions out of the module’s top level.

A practical checklist

  • Find top-level calls that print output, start a demonstration, or perform other example actions.

  • Leave reusable functions and classes defined at module level.

  • Move run-only steps into a main() function.

  • Call main() beneath if __name__ == "__main__":.

  • Import a reusable definition from a small caller and check that the example does not run.

A few more useful answers

Will the `main()` function run when another file imports the module?

Not through the guarded call shown here: on import, __name__ is the module name rather than '__main__', so the condition is false. [S1]

Can I keep helper functions outside the guard?

Yes. Put reusable function and class definitions outside the guard. Put the call that starts the example or script inside main(), and call main() under the guard.

Does the guard stop every statement in the file from running on import?

No. It controls the call to main() beneath it. Other unguarded top-level statements still execute when the module is loaded, so keep run-only actions out of that area. [S1]

Sources

References used for this guide.

  1. [S1] __main__ — Top-level code environment (Python 3.15 documentation)
    docs.python.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work