Fundamentals 13 min read

Master Python Imports: From Basics to Advanced Techniques

This article explains Python's flexible import system, covering regular imports, from‑statement imports, relative imports, optional imports, local imports, and common pitfalls such as circular and shadowed imports, while providing clear code examples and best‑practice recommendations.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Imports: From Basics to Advanced Techniques

As a beginner Python programmer, one of the first things you need to learn is how to import modules or packages, and many occasional Python users are unaware of how flexible the import mechanism really is.

Regular imports

Using the from statement

Relative imports

Optional imports

Local imports

Import pitfalls

Regular imports

Regular imports are the most common way to import modules. The simplest form is: import sys You can import multiple modules in one line: import os, sys, time The Python style guide recommends one import per line, even though a single line saves space.

Modules can be imported with an alias: import sys as system Some sub‑modules must be imported using dot notation, e.g.:

import urllib.error

Using from statement

When you only need a specific part of a module, use from: from functools import lru_cache You can also import everything from a module (not recommended except for tkinter): from os import * Or import several items at once, optionally using parentheses or a backslash for line continuation:

from os import path, walk, unlink, uname, remove
# or
from os import (path, walk, unlink, uname, \
                remove, rename)

Relative imports

PEP 328 introduces relative imports using leading dots to avoid accidental name clashes with the standard library. Example package layout:

my_package/
    __init__.py
    subpackage1/
        __init__.py
        module_x.py
        module_y.py
    subpackage2/
        __init__.py
        module_z.py
    module_a.py

In my_package/__init__.py:

from . import subpackage1
from . import subpackage2

In subpackage1/__init__.py:

from . import module_x
from . import module_y

In module_x.py you can import from the sibling module:

from .module_y import spam as ham

def main():
    ham()

Running the package from the top directory (not from inside the package) allows the relative imports to work. Executing a module directly as a script will raise errors because relative imports are not supported in script mode.

Optional imports

Use a try/except ImportError block to prefer a module but fall back to alternatives:

try:
    from http.client import responses  # Python 3
except ImportError:
    from httplib import responses  # Python 2.5‑2.7
    # further fallbacks …

try:
    from urlparse import urljoin
    from urllib2 import urlopen
except ImportError:
    from urllib.parse import urljoin
    from urllib.request import urlopen

Optional imports are a common technique for writing code that works across versions or provides performance improvements.

Local imports

Importing inside a function limits the import to the function’s local scope, which can be useful for heavy modules that are only needed occasionally:

import sys  # global scope

def square_root(a):
    import math
    return math.sqrt(a)

def my_pow(base_num, power):
    import math
    return math.pow(base_num, power)

if __name__ == '__main__':
    print(square_root(49))
    print(my_pow(2, 3))

Although local imports can reduce start‑up time, the convention is to place all imports at the top of the module.

Import pitfalls

Circular imports

When two modules import each other, an AttributeError occurs. The usual solution is to refactor the code to avoid the circular dependency.

Shadowed imports

If you create a module with the same name as a standard‑library module (e.g., math.py), your module will shadow the standard one, leading to missing attributes such as sqrt.

Summary

The article covered many aspects of Python imports, but there are more advanced topics such as import hooks (PEP 302) and the importlib module in the standard library. Exploring other developers’ code can reveal even more useful tricks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

modulebest-practicesPackageimportsRelative Importoptional-import
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.