Last modified: May 10, 2025 By Alexander Williams

Python Import Statements Guide

Import statements are key in Python. They let you use code from other files. This guide covers syntax and best practices.

Basic Import Syntax

The simplest import statement loads a module. Use the import keyword followed by the module name.


# Import entire module
import math

# Use module functions
print(math.sqrt(16))


4.0

Importing Specific Items

You can import specific functions or classes. This makes code cleaner.


# Import specific function
from math import sqrt

# Use directly
print(sqrt(25))


5.0

Import Aliases

Use aliases for long module names. This improves readability.


# Import with alias
import numpy as np

# Use alias
array = np.array([1, 2, 3])

Relative Imports

Relative imports work within packages. They use dots to show location.


# Import from parent package
from ..utils import helper

Import Best Practices

Group imports by type. Standard library first, then third-party, then local.


# Standard library
import os
import sys

# Third-party
import requests
import numpy as np

# Local
from . import helpers

Avoid wildcard imports. They make code unclear. Use specific imports instead.

For advanced import techniques, see our Python Import System Guide.

Dynamic Imports

Python allows dynamic imports using importlib. This is useful for plugins.


import importlib

# Load module dynamically
module = importlib.import_module('math')
print(module.sqrt(36))


6.0

For more on dynamic loading, check SourceFileLoader Guide.

Common Import Errors

ModuleNotFoundError happens when Python can't find the module. Check your PYTHONPATH.

ImportError occurs when a specific item can't be imported. Verify the item exists.

Circular Imports

Circular imports happen when two modules import each other. They cause problems.

Restructure code or use local imports to fix them. Our resolve_name Guide can help.

Conclusion

Proper import statements make Python code clean and maintainable. Follow best practices for better code organization.

Use specific imports, group them logically, and avoid circular dependencies. This keeps your codebase healthy.