Intermediate   Chapter 87 · 25 min read · Module 7: Python Modules and Packages

Introduction to Modules

Learning objectives
  • After this chapter you can explain what a module is and why modules are useful.
  • You can name the three kinds of modules: built-in, standard library and third-party or your own.
  • You can use dir() and the __name__ attribute to inspect a module.
  • You can describe how Python finds a module using sys.modules and sys.path.
  • You can explain the idea of a namespace and how modules avoid name clashes.

As programs grow, keeping all code in one file becomes hard. The file gets long, names start to clash, and it is difficult to find anything. Python solves this with modules. A module is simply a file that holds Python code, such as functions, classes and variables, which other programs can reuse.

You have already used modules without thinking much about it. Every time you wrote import math or import random you were loading a module written by someone else. The same mechanism lets you organise your own code into separate files.

In this chapter you will learn what a module really is, how Python keeps module names apart using namespaces, and how to inspect any module. The next chapters will show the different forms of the import statement and tour useful built-in modules.

What is a module?

Module: a single Python file, or a built-in component, that contains definitions and statements and can be loaded into another program with import

If you save a file called tools.py with a few functions in it, then tools is a module. Its name is the file name without the .py ending. Another program can load it with import tools and call tools.some_function(). Modules let you write code once and use it in many programs.

Modules give you several benefits. They help you reuse code instead of copying it. They make large programs organised, since related functions live together. They keep names separate, so two modules can both have a function called load without conflict. And they make testing easier, because each part can be checked on its own.

Where do modules come from?

  • Built-in modules are part of the Python program itself, for example sys and builtins.
  • The standard library is a large set of modules installed with Python, such as math, json, datetime and os.
  • Third-party modules are written by other people and installed with pip, such as requests or numpy.
  • Your own modules are the .py files that you write in your project.
Example 1: using a standard library module
import math
print(math.sqrt(49))
print(math.pi)
print(type(math))
print(math.__name__)
7.0 3.141592653589793 <class 'module'> math

The output shows that a module is itself an object, of the type module. Its __name__ attribute holds the module name. Using the dot, as in math.sqrt, you read an attribute of the module object. This is how you reach everything a module defines.

Namespaces keep names apart

Namespace: a mapping from names to objects; every module has its own namespace, so the same name can exist in two modules without conflict

When you write math.pow and pow, you are using two different names. The first is pow inside the math namespace. The second is the built-in pow. They behave a little differently, and Python never mixes them up, because the module name in front tells it where to look.

Example 2: two different pow functions
import math
print(pow(2, 3))
print(math.pow(2, 3))
print(pow is math.pow)
8 8.0 False

Looking inside a module

The built-in dir() function lists the names inside an object. Called on a module it shows its functions, classes and constants. The help() function shows documentation. A module can also keep a short description in its __doc__ attribute, which is the string at the top of the file.

Example 3: exploring a module with dir()
import math
names = [n for n in dir(math) if n in ("sqrt", "floor", "ceil", "pi", "cos")]
print(sorted(names))
print(hasattr(math, "sqrt"))
print(hasattr(math, "banana"))
print(callable(math.sqrt), callable(math.pi))
['ceil', 'cos', 'floor', 'pi', 'sqrt'] True False True False

How Python finds and loads a module

When Python meets import name, it first checks the dictionary sys.modules, which holds every module already loaded. If the module is there, Python reuses it. If not, it searches the folders listed in sys.path, in order: the folder of the running script, then the installed library folders. When it finds the file, it runs the code in it once, builds a module object and stores it in sys.modules.

Because a module is run only on the first import, importing it again is cheap and does not repeat its work. This also means the module object is shared: every part of your program that imports math receives the same object.

Example 4: modules are cached in sys.modules
import sys
import math
print("math" in sys.modules)
import math as m2
print(m2 is math)
print(isinstance(sys.path, list))
print(sys.modules["math"] is math)
True True True True

Making a module object by hand

To see that a module is only an object with attributes, you can create one with types.ModuleType. You can then add names to it as if it were a file. This is not common in real code, but it makes the idea very concrete.

Example 5: a module is an object with attributes
import types
shapes = types.ModuleType("shapes")
shapes.PI = 3.14
shapes.area = lambda r: shapes.PI * r * r
print(shapes.__name__)
print(shapes.area(2))
print(type(shapes).__name__)
shapes 12.56 module
Do not name your own file after a standard module. A file called math.py or random.py in your project can hide the real module and cause confusing errors.

Module files and the __name__ value

Every module has a __name__ attribute. When a file is imported, __name__ is the module name. When the file is run directly as the main program, __name__ is the text "__main__". This is why many scripts end with if __name__ == "__main__":, which runs some code only when the file is run directly, not when it is imported. You will use this pattern when you create custom modules.

Python syntax

Syntax
import module_name
Syntax
module_name.attribute
Syntax
dir(module_name)
help(module_name)
Syntax
if __name__ == "__main__":
    main()

Real-world applications

  • Splitting a large program into files such as database.py, utils.py and main.py.
  • Reusing helper functions across several projects.
  • Using the standard library for maths, dates, files and JSON.
  • Installing third-party modules for web requests, data analysis or graphics.
  • Writing tests that import and check one module at a time.

Common mistakes

Mistake: Naming a file after a standard module, such as random.py.
Fix: Choose unique names so your file does not hide the real module.
Mistake: Using a module's function without importing the module first.
Fix: Add the import line at the top, or you will get a NameError.
Mistake: Expecting the module code to run again on every import.
Fix: A module body runs only on the first import. Later imports reuse the cached module.
Mistake: Writing the file extension in the import, such as import tools.py.
Fix: Write import tools, without .py.
Mistake: Forgetting the module name before an attribute, such as writing sqrt(9) after import math.
Fix: Write math.sqrt(9), or import the name directly.

Important tips

  • Use dir(module) and help(module) to explore unknown modules.
  • Keep module names short, lowercase and without spaces.
  • Put all imports at the top of the file.
  • Group related functions in one module.

Key points summary

  • A module is a Python file that other code can import.
  • Each module has its own namespace.
  • Python caches loaded modules in sys.modules.
  • Python searches sys.path to find modules.
  • dir() lists the names in a module.
  • __name__ is __main__ only when the file is run directly.

Exam and interview points

  • A module is a file with a .py extension containing Python code.
  • Module names are the file name without .py.
  • sys.modules caches loaded modules; sys.path lists search folders.
  • __name__ equals '__main__' for the main script.
  • Each module has a separate namespace.

Quick revision

  • Module = a .py file you can import.
  • Namespace avoids name clashes.
  • dir() lists contents.
  • Modules load once and are cached.
  • __name__ == '__main__' means run directly.

Frequently asked questions

Is a module the same as a package?

No. A module is one file. A package is a folder of modules. Packages are covered in a later chapter.

How do I see what a module contains?

Use dir(module) for the names and help(module) for the documentation.

Does importing a module run its code?

Yes, the top-level code runs once on the first import. Function bodies only run when you call them.

Can I write my own modules?

Yes. Save a .py file in your project folder and import it by its file name without .py.

Why does the module name need a dot?

The dot reads an attribute from the module's namespace, so math.sqrt means the sqrt name inside math.

Practise this chapter

18 practice questions Take the chapter quiz

Related chapters