Python Packages: Importing Local Modules

When a Python project keeps related code in separate files, you need a clear way to use one file from another. Importing local modules lets your program refer to that code through package and module names.

This article shows how to create a package and import its modules, then how to check common import problems.

TL;DR: Import a module through its package name

Put related modules in a package directory, make its parent directory importable, then use the package and module names separated by dots.

  • Use a fully qualified import when callers should keep the module namespace.
  • Use the package-level form to bind the child module directly.
  • For a regular package, an empty initializer file is enough. Namespace packages can follow different rules.

What Is a Python Package?

A package uses a dotted namespace for its modules. A module is commonly one Python file, while a package often maps to a directory containing submodules.

Python’s import reference defines a package by its package search path. A regular package normally has an initializer file, which Python runs when imported. Namespace packages can omit that file under documented rules.

TermTypical formPurpose
Modulenumbers.pyHolds code with its own import name.
Regular packageutilities initializer fileGroups modules and can initialize package names.
Subpackagetext subpackage initializerAdds another level to the dotted name.
DistributionA project installed by a package toolNames the installable project, which may differ from its import name.

An installed distribution and the name used after import are not guaranteed to match. Check a project’s instructions instead of guessing its import name from the installer command.

Import statements name modules inside a namespace, while installation instructions name an installable distribution. Python caches imported modules for the current process and reuses them on later imports until a fresh interpreter starts.

A project may have nested packages. A module inside the text subpackage has a dotted name when the project root is searchable. Dots mark import names, while directory separators mark folders.

The initializer can re-export a function to create a shorter public interface. This makes the top-level import load that function’s module too, so keep the public names deliberate as the project grows.

Python’s import search checks configured locations for a name. A local package can work when launched from its project root and fail from another directory or interpreter.

For this example, use a regular package with an empty initializer. Namespace packages can span multiple locations under Python’s documented rules.

How to create and import a Python package step by step

Create a project root that contains a package directory, then run the importing script from that root. The directory names become the dotted path used in the import statement.

Step 1: Make the package structure

Start with this tree. The top-level script sits beside the package directory, so launching it from the project root makes the package discoverable.

project/
├── main.py
└── utilities/
    ├── __init__.py
    └── numbers.py

Create an empty initializer file for a regular package, then add a function to its numbers module:

def add(a, b):
    return a + b

Keep the initializer lightweight. Python executes its top-level statements during the first package import in a process, so startup actions or noisy printing there can surprise every caller.

Step 2: Import the module by its dotted name

Use a dotted name rather than a folder separator or file suffix. Either form below makes the module’s add function available.

import utilities.numbers as numbers
from utilities import numbers as numbers_from_package

print(numbers.add(4, 5))
print(numbers_from_package.add(4, 5))

Run the demonstrated program from its named file with:

python3 package_import_demo.py

The captured terminal output is:

9
9
exit: 0
ModuleNotFoundError: No module named 'missing_toolkit'
Terminal running package_import_demo.py and showing two successful imports and a missing module error
Both import forms return 9. The last line shows the missing-module error from the deliberate check.

I ran both forms against the same local module and got 9 from each. The final error line comes from a separate deliberate missing-name check in the demo.

Step 3: Choose what name to bind

Use a fully qualified module import when you want the call site to show where a function comes from. An alias shortens repeated calls.

Use from utilities.numbers import add when the caller needs one clearly named object, then call add(4, 5). This binds the name in the current module and can obscure its origin if many modules export the same name. The related AskPython guide to modules and packages covers that naming distinction.

Step 4: Import a child module from the package

You can import the child module through its package, or import one function from that module. Both forms require Python to find the top-level package.

Inside a package, a relative import can refer to a sibling module. It needs package context, so launch a package module with the interpreter’s module option from the directory above it.

The Python tutorial explains wildcard imports and the package’s public-name list. Wildcard imports can hide where a name came from, so explicit imports keep dependencies visible.

Prefer explicit imports in application code because they make dependencies visible.

Fix package import problems

When an import fails, check the requested name and the active interpreter’s search locations. The final exception often separates a missing module from a missing name within one.

SymptomLikely checkNext step
ModuleNotFoundErrorIs the package parent on this interpreter’s import path?Run from the project root or install the dependency into the interpreter being used.
ImportError for a nameDid the module load but lack that name?Check the spelling and definitions in the imported module.
Works from one folder onlyDoes the current launch location change the search path?Run from the project root or use a package entry point.
Import resolves to an unexpected fileDoes a local file shadow a standard or installed module?Rename the conflicting file and check the resolved module location.

Python checks configured import locations. Their contents depend on how the interpreter starts, including the launch location and environment. A sibling folder is not found just because it exists elsewhere on disk.

Check the current process with this short diagnostic:

import sys
print(sys.executable)
print(*sys.path, sep="\n")

Confirm the executable is the interpreter where the dependency was installed. Then check whether the project root or environment’s package directory appears in the listed locations.

A missing third-party import can mean the installer name and import name differ. Check the project’s documented spelling and use the same interpreter for installation. Adding arbitrary folders to the search path ties behavior to where you launch the program.

The demo’s deliberate missing-name check returned No module named ‘missing_toolkit’. The requested name was absent from that process. Check its spelling, interpreter and search locations before changing package files.

Conclusion

Think of a package import as a dotted route from an importable project root to a module. Keep the tree and the command that launches it together, then choose an import form that makes each name’s source clear.

FAQ

These short answers address common package import questions.

How do I import a module from a Python package?

Use a dotted import such as import utilities.numbers, or write from utilities import numbers to bind the child module directly. The package parent must be on Python’s import path.

Does every Python package need an __init__.py file?

Regular packages typically contain __init__.py, but namespace packages can omit it under Python’s namespace package rules.

Why does Python say No module named when my folder exists?

Python must search the folder’s parent, not merely see the folder on disk. Check the active interpreter, launch directory, requested import name and sys.path.

Can the package installation name differ from its import name?

Yes. A distribution package name used by an installer can differ from the name imported in Python, so follow the project’s documentation.

Pankaj Kumar
Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 261