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()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.