Ch. 9 · Python

Python Imports and Side Effects

Python Imports and Side Effects. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readadvancedupdated Oct 3, 2026

Importing executes a module’s top-level code on initial loading. Keep startup side effects deliberate and separate reusable definitions from program entry.

Before you start

You should know Python functions, collections and exceptions. Use a small isolated script or interactive session to trace the example. Pay attention to when objects are created and when work executes; iteration, binding and mutation can happen at different points in a program.

The practical goal is to reason through this situation: Use an if __name__ == '__main__' entry boundary for command execution. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Separate definitions from execution

Reusable functions belong at module level without starting the program immediately.

Step 2: Use an entry boundary

Invoke the CLI under the main check.

Step 3: Make imports testable

Importing should not unexpectedly open servers or modify user files.

Worked scenario

Use an if __name__ == '__main__' entry boundary for command execution.

def main():
    print('CLI started')
if __name__ == '__main__':
    main()
python

Running the file invokes main; importing it exposes the function without printing the message. Other top-level statements still execute during initial import, so the guard does not excuse unrelated side effects elsewhere.

Common mistake

Starting servers or modifying files during import makes tests and reuse fragile.

Verify the behavior

Import in a fresh process and assert no CLI output or external work; then execute the file and verify its entry behavior.

Interview exercise

Design an importable CLI module.

Answer and reasoning

Expose functions without executing the CLI automatically, then invoke them from an explicit entry point.

Continue learning

Compare the scenario with the Python interview questions and test your understanding with the Python MCQs. For terminology and implementation details, consult the reference material.

More in Python

read ✓Python · hard

Python asyncio.gather and Timeouts

Run coroutines concurrently with asyncio.gather, enforce timeouts, and handle partial failures and cancellation correctly.

~2 min readread →
read ✓Python · mid

Python Bounded Async Worker Queues

Use asyncio.Queue and a fixed worker pool to bound pending work. Trace backpressure, shutdown and failure ownership.

~3 min readread →
read ✓Python · mid

Python Asyncio and Blocking Functions

Python Asyncio and Blocking Functions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc