Concepts / Testing Python Code

Testing Python Code

The __name__ attribute tells your code how the current module is being used.

  • Programming

The Two Ways a File Runs

A Python file can be used in two different ways: a user can run it directly as a program, or another file can import it as a module. Python uses the special __name__ attribute to distinguish these situations. That distinction lets you keep reusable code available for import while preventing test or demonstration code from running unexpectedly.

What do you think happens?

Suppose a file named module_using_name is run directly and then imported by another script. What value does __name__ have in each situation?

  • __main__ when run directly; module_using_name when imported

  • module_using_name in both situations

  • __main__ in both situations

Reveal answer
Answer:

__main__ when run directly; module_using_name when imported

Python sets __name__ to __main__ for the file the user runs directly. When another script imports that file, Python sets __name__ to the module's name instead.

Reading the __name__ Value

The __name__ attribute tells your code how the current module is being used. When the user runs the file directly, Python gives that file the value __main__. When another script imports the file, Python gives it the module's name. Your code can check this value and choose whether to execute a particular block.

Run directlythe file is the mainprogram__main____name__ valueImportmodule_using_nameanother script loads thefilemodule_using_name__name__ valuesetssets
What value does __name__ contain when the same file is run directly versus imported?
Key point

The two underscores on each side are part of the attribute name. Write __name__ exactly, and compare it with the exact string '__main__'.

The Guard as a Gatekeeper

Code walkthrough
if __name__ == '__main__':
    print('Standalone test code runs here')
  1. 1
    Python evaluates whether __name__ equals '__main__'.
  2. 2
    If the file was run directly, the condition is true and the indented code executes.
  3. 3
    If the file was imported, the condition is false and the indented code is skipped.
  • The if statement checks the module's usage context.
  • __name__ is the attribute being inspected.
  • The comparison uses the exact string '__main__'.
  • The indented block is protected by the condition.

The if __name__ == '__main__': statement acts as a gatekeeper. It allows test or demonstration code through only when the file is being executed directly. When the file is imported, the condition is false, so that protected code does not run automatically.

Load Python file__name__ =='__main__'check the usage contextStandalone test codeexecutes when trueReusable functionsavailablefor importing codeProtected codeskippedwhen the file is importedevaluatetruefalsekeep module usable
Which path does the file follow when it runs directly, and which path does it follow when it is imported?

A Calculator Module

Imagine a calculator module containing add and multiply functions. Other programmers should be able to import those functions. The same file can also contain tests that check the functions when the file is run directly. The guard separates these two purposes.

python
Worked example

Tracing the calculator module

Determine what happens to the test output when the calculator file is run directly and when another script imports it.

  1. 1
    Direct execution

    Python sets __name__ to '__main__'. The condition is true, so the two print statements inside the guarded block execute and display the test results.

  2. 2
    Importing

    Python sets __name__ to the calculator module's name rather than '__main__'. The condition is false, so the two test print statements are skipped.

  3. 3
    Reusable code

    The add and multiply functions remain available for another programmer to use when the module is imported, without the test output running automatically.

Result

Direct execution runs the test code; importing provides the functions without running the guarded test output.

Output
5
6

What Runs in Each Context

Code or valueFile run directlyFile imported
__name____main__The module's name
Code inside the guardExecutesIs skipped
Reusable functionsCan be usedAvailable for the importing program
Test or demonstration outputRuns when placed inside the guardDoes not run when placed inside the guard

The guard separates standalone behavior from reusable module behavior.

add and multiplyreusable functionsadd and multiplyavailable after importTest outputinside the guardTest outputskipped after importremains availableguard prevents execution
Which part remains usable in both contexts, and which part is restricted to direct execution?

Mistakes with the Guard

  • Common mistake

    Using the wrong attribute spelling

    What it looks like
    if name == '__main__':
    Why it fails

    The pattern depends on the special __name__ attribute, including both pairs of double underscores.

    Do this instead
    Write __name__ exactly.
  • Common mistake

    Comparing with the wrong string

    What it looks like
    if __name__ == 'main':
    Why it fails

    The direct-execution value is the exact string '__main__', including the double underscores.

    Do this instead
    Compare __name__ to '__main__'.
  • Common mistake

    Putting test output outside the guard

    What it looks like
    print(add(2, 3))
    
    if __name__ == '__main__':
        print('done')
    Why it fails

    The test print statement is not protected by the guard, so it is not separated from the reusable module code.

    Do this instead

    Place standalone test or demonstration statements inside the if __name__ == '__main__': block.

Best practice

Use the __name__ pattern when a file is designed to work both as a standalone program and as an importable module. It communicates that the file has reusable code while keeping its test or demonstration behavior controlled.

Apply the Pattern

EASY

Write a small module containing a function named add and a test print statement. Put the test statement inside an if __name__ == '__main__': guard. Then describe what happens when the file is run directly and what happens when another script imports it.

Hints
  • Use the exact attribute name __name__.
  • Compare it with the exact string '__main__'.
  • The test statement belongs inside the indented guarded block.
  1. 1
    Python sets __name__ to '__main__' for the file the user runs directly. For an imported file, Python sets __name__ to the module's name. The if __name__ == '__main__': pattern checks that distinction and protects standalone test or demonstration code. As a result, reusable functions can be imported without automatically running the module's test output.

Key Takeaways

  • The __name__ attribute identifies whether a file is being run directly or imported.
  • A directly run file has __name__ equal to '__main__'.
  • An imported file has __name__ equal to its module name.
  • The if __name__ == '__main__': guard runs its block only during direct execution.
  • The guard separates reusable module code from standalone test or demonstration code.

Related concepts

More concepts starting with T