intermediate

Modules & Imports

By DataPlayArena Technical Review BoardUpdated 2026-07-127 min readRuntime Verified

Overview

Organize your code by dividing it across multiple files, and import them as modules.

Learning Objectives

  • Import code using import, from, and as.
  • Prevent circular import dependency errors.
  • Use name to create script entry points.

Concept Explanation

Every Python file is a module. Importing a module runs its code and binds its namespace. Use if __name__ == '__main__' to write code that only executes when the script is run directly, and not when it is imported into another file.

Code Examples

Example 1 — Basics

This example introduces the fundamental syntax and concepts.

python
import math
print(math.sqrt(16))

Example 2 — Everyday Usage

This example demonstrates a realistic scenario handling business parameters.

python
from datetime import datetime as dt
print(f'Current time is: {dt.now()}')

Example 3 — Advanced Example

This example shows clean, production-grade code structure following senior development standards.

python
def run_operations():
    print('Running standalone calculations.')

if __name__ == '__main__':
    # Executes only if run directly
    run_operations()

Visual Flow

The following execution flow represents the step-by-step evaluation inside the interpreter:

text
Trigger Import → Search sys.modules → Load code → Execute module statements → Bind namespace

Common Mistakes

Review these common pitfalls when working with this topic:

  • Creating circular imports where module A imports B, and B imports A.
  • Using wildcard imports (from math import *) that pollute namespaces.
  • Naming local scripts the same as standard modules (e.g. naming your file 'math.py').
  • Forgetting script check guards inside files that are meant to be imported as libraries.

Best Practices

Enforce these Pythonic best practices in your codebase:

❌ Don't
python
from math import * # Pollutes namespace
✅ Do
python
import math # Clean namespace references

Quick Revision

Use these key summaries for last-minute revision:

  • Modules are standard .py files.
  • import statement exposes code tools.
  • Wildcard imports make code harder to debug.
  • name checks if a file is the main script.
  • Python caches imports inside sys.modules.
  • Avoid shadowing standard library names.
DPA

DataPlayArena Technical Editorial Board

Curated & maintained by enterprise data platform engineers with 10+ years in distributed systems.

Runtime Verification Standards: Every code example, query, and architecture diagram in this tutorial is compiled and verified against real runtimes (Apache Spark 3.5, Python 3.11, PostgreSQL, and DuckDB). If you spot any errata or want to suggest improvements, please submit feedback.