Python online course

What Are Modules in Python?

Learn what Python modules are, why they are useful, how imports work, where Python finds modules, and how to create and use your own modules.

A module is a reusable unit of Python code, commonly stored in a single file. Modules help you organize a program into focused parts instead of placing every function, class, and variable in one large file.

An ordinary Python source module usually has the .py filename extension. For example, greetings.py can contain code related to displaying greetings, while main.py can use that code.

Why Python modules are useful

Modules are useful when a program grows beyond a few lines. You can divide a large program into smaller, more manageable files and keep related functionality together.

  • Organization: Put related functions, classes, constants, and other definitions in one focused file.
  • Reuse: Import the same definitions into multiple programs instead of copying the code.
  • Maintenance: A change to one module can improve every program that uses it.
  • Separate namespaces: Names defined in different modules are kept apart unless you explicitly import or reference them.

A namespace is a mapping between names and the objects those names refer to. Each module provides its own namespace. This reduces accidental name conflicts and makes the origin of a definition clear.

What a module contains

A module can contain functions, classes, variables, constants, imported names, and executable statements. Each named item belonging to the module is called an attribute.

For example, a module named greetings might have these attributes:

DEFAULT_GREETING = "Hello"

def greet(name):
    return f"{DEFAULT_GREETING}, {name}!"

The module object is greetings. The function and constant inside it are attributes of that module: greetings.greet and greetings.DEFAULT_GREETING. The dot in this syntax is called dot notation.

Importing a module

The import statement makes a module available to the current Python file. With the usual form, Python gives you the module under its module name, and you use dot notation to access its contents.

import math

result = math.sqrt(25)
print(result)

Here, math is the module object, and sqrt is an attribute of that object. The result is 5.0.

Import aliases

You can give an imported module a shorter local name with as:

import math as m

result = m.sqrt(25)

An alias changes the name used in the current file; it does not rename the module itself.

Importing selected names

The from ... import ... form brings a particular name from a module directly into the current namespace.

from math import sqrt

result = sqrt(25)

Because sqrt was imported directly, you call it without the math. prefix. You can also use an alias for the selected name:

from math import sqrt as square_root

result = square_root(25)

Selected-name imports can be convenient, but use them carefully. A local variable or function with the same name can conflict with the imported name or overwrite it. The full-module form, such as math.sqrt(), makes the source of a name explicit and often improves readability.

Common ways to import Python code

SyntaxWhat becomes availableHow it is usedWhen it is appropriate
import moduleThe module objectmodule.nameUse when clarity and namespace separation matter.
import module as aliasThe module object under an aliasalias.nameUse for a conventional or convenient shorter name.
from module import nameOne selected attributenameUse when the name is unambiguous and direct access is helpful.
from module import name as aliasOne selected attribute under an aliasaliasUse to avoid a local name conflict or clarify a name.

How Python finds modules

Before Python can import a module, it must be able to locate it. Python checks a set of locations called the module search path.

For beginner projects, common locations include:

  • The directory containing your program or the current project directory.
  • Python's standard library, which is included with Python.
  • Locations containing installed third-party packages, often associated with the Python interpreter or virtual environment you are using.

If a custom module is in the same project directory as the script that runs it, a simple import usually works. More advanced projects can organize modules into packages and configure environments so Python can find installed code.

Standard-library modules and libraries

The standard library is Python's built-in collection of modules for common tasks. The math module provides mathematical functions, and modules such as datetime, random, and json support dates, random values, and JSON data.

A library is reusable code intended for general-purpose tasks. A library may consist of one module or several related modules. A package is a larger importable structure used to organize related modules. In short, a module is often one file, while a package can group multiple modules into a larger structure.

TermMeaningExample
ModuleA reusable unit of Python code, commonly stored in one source file.math or greetings.py
AttributeA named item belonging to a module.math.sqrt
LibraryReusable code for general-purpose tasks; it can contain one or many modules.The Python standard library
PackageA way to organize related modules into a larger importable structure.A project package containing utility modules
NamespaceA mapping of names to objects that keeps definitions identifiable and separate.math.sqrt versus statistics.mean

Creating and using a custom module

Create a project directory containing these two files:

module_demo/
    greetings.py
    main.py

Step 1: Create the module

Put a constant and a function in greetings.py:

DEFAULT_GREETING = "Hello"

def greet(name):
    return f"{DEFAULT_GREETING}, {name}!"

DEFAULT_GREETING and greet are attributes of the greetings module.

Step 2: Import the module from another file

In main.py, import the complete module and use dot notation:

import greetings

print(greetings.DEFAULT_GREETING)
print(greetings.greet("Ada"))

Because both files are in the same directory, Python can normally find greetings.py when main.py runs.

Step 3: Import selected names instead

You can import only the function and constant you need:

from greetings import DEFAULT_GREETING, greet

print(DEFAULT_GREETING)
print(greet("Ada"))

Compare the two styles: greetings.greet("Ada") identifies the module that owns the function, while greet("Ada") uses the selected name directly.

Namespaces help avoid naming collisions

Suppose two modules both define a function named format_data. Importing the modules and using their prefixes keeps the two functions distinct:

import csv_tools
import json_tools

csv_result = csv_tools.format_data(data)
json_result = json_tools.format_data(data)

Both functions can be called because their full names are different. Without the module prefixes, importing two selected names with the same name would create a conflict.

Exploring module attributes

During learning, dir() can show names available on a module:

import math

print(dir(math))

The output includes attributes supplied by the module. Some names support internal implementation details, so use official documentation to learn which attributes are intended as the module's public API.

You can learn more about displaying module content in Display Module Content.

Module loading and reuse

Importing lets a program reuse code defined elsewhere instead of copying that code into every file. During one running Python program, imported modules are normally loaded once and then reused from Python's module cache. This avoids repeating the module's setup work every time the same module is referenced.

In advanced interactive development, the importlib.reload() function can reload a module after its source changes:

import importlib
import greetings

importlib.reload(greetings)

Reloading is mainly useful while experimenting in an interactive session. It is not the usual workflow for a finished application; normally, restart the program after changing a module.

Troubleshooting imports

ModuleNotFoundError

A ModuleNotFoundError means Python could not find the requested module. Check that:

  • The custom file is in the project directory or another location on the module search path.
  • The filename matches the import exactly, including spelling and capitalization where relevant.
  • You are running the intended Python interpreter and virtual environment.
  • A local file has not been given a confusing name that hides a standard-library or installed module.

AttributeError after importing

An AttributeError can occur when the requested attribute is not defined under that name. Check the spelling, capitalization, and documented API. During exploration, dir(module) can help show available names. Also verify that Python imported the file you intended rather than a similarly named local file.

NameError after a selected-name import

A NameError may mean that you imported a different name than the one you called, overwrote the imported name later, or used the wrong access style. For example:

from math import sqrt

print(sqrt(25))       # Correct
# print(math.sqrt(25))  # math was not imported here

Use a clear alias when necessary, or use import math when explicit module prefixes make the code easier to understand.

An unexpected module is imported

A local file with the same name as a standard-library or third-party module can shadow the module you intended to import. Rename the local file to a distinctive project-specific name. If an old generated cache file preserves confusion during local testing, remove it and restart the interpreter.

Key points

  • A module is commonly one reusable Python source file with a .py extension.
  • Modules group related logic and data and make larger programs easier to organize.
  • Functions, classes, variables, and other named definitions in a module are its attributes.
  • import module is used with dot notation, such as module.function().
  • from module import name makes a selected name available directly, so use it as name.
  • Python resolves imports through its module search path, including the project directory, standard library, and installed package locations.
  • Modules provide namespaces that help prevent accidental naming conflicts.
  • Imported modules are normally loaded once per running program and reused from the module cache.

For the related syntax and practical usage, continue with Import Modules. You may also review Python Overview, Run Python Code, and Variable Scopes.