Skip to content

Module 14 · Python Modules and Packages — topic 1 of 13

Modules

What a module is, why programs are split into modules, how importing a module creates a module object with its own namespace, and how Python caches imported modules.

Beginner 8 min read·Lesson 209 of 306 in Python Programming

Learning objectives

  • Explain what a module is and why modules exist
  • Access a module's contents with dot notation
  • Describe how Python loads and caches modules

Definition

A module is a file of Python code — usually a .py file — whose functions, classes and variables can be used by other code through import. Each module has its own namespace, so names in different modules don't clash.

Introduction

A program with 5,000 lines in one file is hard to read and harder to change. Modules let you split code into files, each with one job, and reuse them across programs.

Why it matters

Modules are how Python code is organised and shared — from your own helper files to the huge standard library and third-party packages.

Detailed explanation

Any .py file is a module. Its name is the file name without .py: greetings.py is the module greetings.

import greetings runs the module's code once, top to bottom, and creates a module object. Its functions and variables become attributes: greetings.greet(...).

Each module has its own global namespace, so a variable called count in one module is separate from count in another.

Python caches imported modules in sys.modules. Importing the same module again returns the cached object without re-running its code.

Every module has a __name__ attribute. The file you run directly has __name__ == "__main__"; imported modules have their own name.

A string at the top of a module is its docstring (module.__doc__), which describes what the module provides.

Python finds modules by searching the directories in sys.path: the script's folder (or the current directory), then the standard library, then installed packages.

Syntax

Python
import math
print(math.sqrt(16))
print(math.pi)
print(math.__name__)
  • import loads a module once.
  • Use module.name to access contents.
  • Each module has its own namespace.

Code examples

Using a standard module

Python
import math
print(math.sqrt(16), round(math.pi, 4))
print(type(math).__name__, math.__name__)
Output
4.0 3.1416
module math

Names and __name__

Python
import random
print(random.__name__, "choice" in dir(random))
print(__name__)
Output
random True
__main__

More examples

Creating and importing a module

Python
from pathlib import Path
import importlib
import sys
Path("greetings.py").write_text('''"""Greeting helpers."""
DEFAULT = "Hello"
def greet(name, word=DEFAULT):
return f"{word}, {name}!"
print("greetings module loaded")
''', encoding="utf-8")
importlib.invalidate_caches()
import greetings
import greetings # cached: the module code doesn't run again
print(greetings.greet("Asha"))
print(greetings.__doc__, greetings.DEFAULT)
print("greetings" in sys.modules)
Output
greetings module loaded
Hello, Asha!
Greeting helpers. Hello
True

Step-by-step explanation

  • The example writes greetings.py next to itself so it can be imported; normally you'd create the file in your editor.
  • importlib.invalidate_caches() makes sure Python notices a module file created while the program is running.
  • The 'loaded' message prints once even though the module is imported twice, because the second import uses sys.modules.

Expected output

Running “Creating and importing a module” prints exactly:

TextOutput
greetings module loaded
Hello, Asha!
Greeting helpers. Hello
True

Practical applications

  • Splitting an app into models.py, views.py and utils.py.
  • Reusing a helper module in several scripts.

Best practices

  • Give each module one clear purpose.
  • Add a module docstring.
  • Avoid naming files after standard modules.

Common mistakes

Naming a file like a standard module

Avoid

# your file is called random.py
import random
random.randint(1, 6) # AttributeError

Prefer

Rename your file, e.g. dice.py

Your file shadows the standard module because the script's folder is searched first.

Important notes

  • Built-in modules such as sys are compiled into the interpreter and have no .py file.

Key takeaways

  • A module is a .py file imported by name.
  • Importing runs it once and caches it.
  • Each module has its own namespace.

Try it yourself

  1. 1
    Create a temperature.py module with c_to_f and f_to_c and use it from another script.
  2. 2
    Print the docstrings of the math, json and random modules.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions cover the “Python Modules and Packages” module. Answers and explanations are revealed after you submit.

  • ModerateWhat happens the second time a module is imported in the same program?
  • ModerateCode under if __name__ == "__main__": runs when…
  • ModerateWhat is printed?
Practise this module