šŸŽ‰ 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
šŸ’¼ Servicesā„¹ļø Aboutāœ‰ļø ContactView Pricing Plansfrom $10

Python Packages: Imports, __init__, and Layout

Python Modules🟢 Free Lesson

Python Packages: Imports, init, and Layout

Importing looks like a single statement, but it triggers a search, a compilation step, an execution of the target module, and a cache write — and every confusion about package layout traces back to one of those four stages. Circular import errors, code running at import time, different files seeing different versions of a module, and dependencies loading slowly on startup are all the same underlying questions asked in different places. This lesson walks through resolution order, package structure, the difference between absolute and relative imports, lazy and optional imports for heavy dependencies, and the concrete fixes for cycles that appear as your project grows past one file.

What You'll Learn

  • 1Trace how Python resolves a module name and what lands in sys.modules
  • 2Structure a package so __init__.py defines a deliberate public surface
  • 3Choose absolute or relative imports consistently and avoid accidental shadowing
  • 4Diagnose and break circular imports with lazy loading and layering

What happens when you write import

When an import executes, Python first checks sys.modules; if the name is already there, you get the cached object and nothing else happens. That caching is why a module's top-level code runs exactly once per process, why monkey-patching in a test can leak between test cases, and why two files importing the same module share state. A missing name starts a search over sys.path, which combines the script directory, PYTHONPATH, installation directories, and any paths appended at run time — the order matters, because the first match wins.

The shadowing consequence is the classic trap: a file named random.py or types.py sitting next to your script takes precedence over the standard library module of the same name, because the script's directory is first on the path. Likewise, import package.module executes package/__init__.py before package/module.py, so anything written at the top level of __init__.py runs at import time, including expensive work you may have assumed was deferred.

python
import importlib
import sys

print("json" in sys.modules)            # False before the first import
import json
print("json" in sys.modules)            # True — now cached

module = importlib.import_module("json")
print(module is sys.modules["json"])     # True — same object, no re-execution

reloaded = importlib.reload(module)      # runs the top-level code again
print(reloaded is module)                # True — object identity preserved

print(sys.path[0])                       # the script's directory, first

importlib matters for three jobs: importing a module whose name is only known at run time, reloading after a code change in a long-running process, and inspecting modules without binding them to a local name. It is also the tool behind plugin systems, which discover entry points and import them by string.

Package layout and what init.py is for

A package is a directory with an __init__.py, and the file's job has narrowed over time: it no longer merely marks the directory, it declares what the package exposes. A minimal __init__.py may be empty, but a good one re-exports the names callers should use, sets a __version__, and keeps internal modules out of the public namespace. The benefit is refactoring freedom — internals can move without breaking importers that only ever import from the package root.

Directory layout is a design decision, not an accident. Flat modules suit small scripts; a single package with subpackages suits libraries; splitting into core, io, and cli packages suits applications. Whatever shape you choose, keep the rule that dependency arrows point inward: higher layers import lower ones, and the lower layers never import from above. That single convention eliminates most cycles before they exist.

Architecture Diagram
reportkit/
ā”œā”€ā”€ __init__.py          # re-exports build_report, __version__
ā”œā”€ā”€ core.py              # domain logic, imports nothing from reportkit
ā”œā”€ā”€ io/
│   ā”œā”€ā”€ __init__.py
│   ā”œā”€ā”€ readers.py        # may import reportkit.core
│   └── writers.py
└── cli.py               # may import reportkit.core and reportkit.io
python
# reportkit/__init__.py
from reportkit.core import build_report, summarise
from reportkit.io.writers import write_csv

__version__ = "1.4.0"
__all__ = ["build_report", "summarise", "write_csv", "__version__"]

Keeping __all__ accurate makes from reportkit import * predictable for quick scripts, documents the intended surface for reviewers, and gives dir() and autocomplete something to follow. When a name is internal, leave it out and do not re-export it — importers that reach into _private modules are depending on structure you never promised.

Absolute versus relative imports

Absolute imports name the module from the package root: from reportkit.io import readers. Relative imports start from the current package: from . import readers or from ..core import build_report. Python's style guidance favours absolute imports because they are unambiguous — a reader can resolve the name without knowing where the file lives — while relative imports are shorter inside deep package trees.

The rule that prevents the notorious error is that a relative import can only be used inside a package. Run a module as a script, with python reportkit/cli.py, and Python treats it as a top-level module with no package context, so from . import readers fails with a complaint about attempted relative import in a non-package. The fix is to run with python -m reportkit.cli, which imports the file as part of its package and gives relative imports the context they need.

python
# reportkit/io/readers.py
import csv
from reportkit.core import normalise          # absolute: clear, refactor-safe
from ..utils import open_text                 # relative: shorter in deep trees

def read_rows(path):
    with open_text(path, encoding="utf-8") as handle:
        for row in csv.DictReader(handle):
            yield normalise(row)

# python reportkit/cli.py      -> ImportError: attempted relative import
# python -m reportkit.cli      -> works, package context present

Mixing both styles for the same dependency is the habit to break. Pick absolute imports as the default, use relative ones only within a package when they genuinely read better, and let a linter enforce the choice so the codebase stays navigable.

Lazy and optional imports

Importing at the top of a module is a contract: the dependency must be installed and must load every time the module loads, even on paths that never use it. For heavyweight libraries — scientific stacks, image processors, cloud SDKs — that contract costs seconds of start-up and breaks environments where the dependency is genuinely optional. Moving the import inside the function defers both the cost and the requirement.

Optional imports follow the same shape with error handling: try to import the fast implementation, fall back to the standard library version when it is absent. The pattern must be deliberate about which behaviour is the default, because a silent fallback that changes performance characteristics is hard to notice. Record which path was chosen, either in a log line or an attribute on the module, so runtime reports can explain a slow run.

python
# top-level: paid on every import, even when unused
# import numpy as np

def summarise(values):
    try:
        import numpy as np            # deferred until this function runs
    except ImportError:
        return {"total": sum(values), "backend": "builtin"}
    array = np.asarray(values, dtype=float)
    return {"mean": float(array.mean()), "backend": "numpy"}

def load_parser():
    import orjson as json             # fast path when installed
    return json

try:
    import orjson
except ImportError:
    import json as orjson             # standard-library fallback

print(summarise([1, 2, 3])["backend"])   # numpy if installed, else builtin
print(orjson is not None)                # True either way

Two refinements worth adopting: cache the result of an optional import in a module-level variable so the try block runs once, and expose the chosen implementation as a name such as json_backend rather than letting every call site repeat the fallback logic.

Diagnosing circular imports

A cycle appears when module A imports B and B imports A, usually one level deeper than the people involved realise: cli imports core, core imports io, and io imports core. Because sys.modules caches partially initialised modules, one side of the cycle receives an incomplete object and raises ImportError for a name that definitely exists — a message that reads like a typo but is really an ordering problem.

Three fixes exist, in order of preference. Restructure so the cycle does not exist by extracting shared code into a third module that both sides import. Move the offending import inside the function that needs it, deferring resolution until both modules are fully loaded. As a last resort, use import module and reference attributes as module.name at call time, which delays the attribute lookup until after initialisation completes. Annotations and string forward references solve the same problem for type hints.

python
# cycle: audit.py imports settings, settings imports audit for a default

# Fix 1 — defer the import to call time
def audit_path(path):
    from project.settings import ALLOWED_ROOTS     # resolved when called
    return path.startswith(ALLOWED_ROOTS)

# Fix 2 — reference lazily through the module object
import project.settings as settings                # no from-import at load

def root_allowed(path):
    return path.startswith(settings.ALLOWED_ROOTS)

# Fix 3 — break the cycle structurally
# settings.py no longer needs audit: move the default into config.py

The structural fix is the only one that removes the design smell. Deferred imports buy time and are perfectly legitimate for performance, but a codebase with many of them has dependency arrows pointing in both directions, and that bidirectionality is what makes the package hard to reason about.

Choosing an import form

The surface syntax is small, but each form carries a different promise about coupling, timing, and namespace pollution. The table below is the decision list to keep in mind while writing imports.

FormWhat it doesUse it when
import osBinds the module nameYou call os.path.join occasionally
import os.path as opBinds an aliasThe name is used constantly and os.path is verbose
from os import pathBinds one attributeSingle name used repeatedly in the module
from pkg import modImports a submodule objectThe submodule is stable public surface
from . import siblingRelative, same packageInside a package where context is unambiguous
from ..core import fRelative, parent packageDeep trees where absolute names get long
importlib.import_module(name)Resolves a string at run timePlugins, entry points, configuration-driven loading

Whichever form you choose, keep imports at the top of the file in standard groups — standard library, third party, then local — with a blank line between groups. That convention is not cosmetic: it lets reviewers see dependencies at a glance, keeps tooling from having to guess, and makes an accidental new third-party dependency visible in the diff rather than buried in a function body.

Common Mistakes

Naming a local file after a standard library module and shadowing it

Fix: Rename your file, because the script directory wins on sys.path and every import silently resolves to your version

Doing expensive work at the top level of __init__.py

Fix: Keep __init__ to re-exports and metadata; defer heavy initialisation to an explicit function

Running a package module as a script and hitting relative import errors

Fix: Execute with python -m package.module so the file is imported with its package context

Patching sys.modules entries in tests without restoring them

Fix: Use monkeypatch or save and restore the entry, since the cache is process-wide

Resolving a circular import with repeated deferred imports everywhere

Fix: Extract the shared code into a lower layer so the cycle disappears structurally

Best Practices

  • Import from the package root and keep internal modules private by convention
  • Group imports as standard library, third party, and local, one blank line between
  • Set __all__ in __init__.py to declare the public surface explicitly
  • Defer heavyweight optional imports into the functions that need them
  • Run package entry points with python -m for consistent resolution and error messages

Interview Questions

Q1: What happens on the second import of an already imported module?

Nothing executes again. Python returns the cached object from sys.modules, which is why top-level code runs once per process and why reload is needed to re-execute it.

Q2: Why does a circular import sometimes raise ImportError for a name that exists?

Because one module in the cycle is still only partially initialised when the other imports from it; the attribute has not been assigned yet. Fix it by deferring the import, restructuring the layers, or referencing the module attribute at call time.

Q3: Difference between import os.path and from os import path?

The first binds the name os to the package and accesses path through it; the second binds path directly in the current namespace. Behaviour is identical, but the direct binding can be shadowed by a local name and changes how the dependency reads at the top of the file.

Key Takeaways

  • sys.modules caches modules, so import runs top-level code exactly once
  • __init__.py defines the package surface; keep it to re-exports and version metadata
  • Absolute imports read cleanly everywhere; relative imports need package context
  • Lazy imports cut start-up cost and make heavy dependencies optional
  • Circular imports are layering problems — defer to buy time, restructure to fix
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
ā˜†ā˜†ā˜†ā˜†ā˜†
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement