Importing Modules in Python with Examples

Importing Modules in Python with Examples

Table of Contents

In Python, module names must follow identifier rules. That means names containing dashes (-), spaces, or starting with numbers cannot be imported using the standard import statement. The dash is interpreted as a subtraction operator, which makes direct imports invalid.

Recommended Approach: importlib

The importlib module is the correct and future-proof way to import modules dynamically using a string name. It bypasses the syntax limitations of the standard import statement and is fully supported in modern Python versions.

import importlib

# Works even if the module name contains a dash or starts with a number
my_module = importlib.import_module("my-module")

# Use the module normally
my_module.some_function()

This is the preferred solution in for programmatic or dynamic imports.

Alternative Options (Use with Caution)

__import__() (Not Recommended)

Python’s built-in __import__() function can technically load such modules, but it is considered low-level and harder to read or maintain.

my_module = __import__("my-module")

Use this only if you are maintaining legacy code.

Rename the File (Most Pythonic Solution)

The best long-term solution is to rename the module file to follow Python naming conventions:

my-module.py  →  my_module.py

Then import it normally:

import my_module

This approach improves readability, tooling support, and maintainability.

exec() (Strongly Discouraged)

Using exec() to run an import statement dynamically is possible but unsafe and difficult to debug.

exec("import my_module as mod")

Avoid this method unless there is no alternative and the input is fully trusted.

Important Notes for 2026

imp Module Is Gone

The imp module was officially removed in Python 3.12. Any examples using imp.load_source() or similar APIs are obsolete.
Always use importlib or importlib.util instead.

PyPI Names vs Import Names

Many Python packages use dashes in their distribution names but underscores in their import names:

pip install scikit-learn
import sklearn

Python is known for its simplicity, readability, and vast ecosystem of reusable code. One of the core features that enables this flexibility is modules. Instead of writing everything from scratch, Python allows developers to import modules and reuse existing functionality efficiently a concept that is strongly emphasized in Python Training Online programs to help learners write clean, modular, and maintainable code.

Understanding how to import modules in Python is a fundamental skill for anyone learning Python, whether you are a beginner or an experienced developer working on large-scale applications.

This provides a complete, practical guide to importing modules in Python, covering syntax, variations, best practices, and real-world examples.

What Is a Module in Python?

A module in Python is a file that contains Python code, such as:

  • Functions
  • Classes
  • Variables
  • Executable statements

Any file with a .py extension can be treated as a module.

Example of a Simple Module

Create a file named math_utils.py:

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

def subtract(a, b):
    return a - b

This file is now a Python module that can be imported into other programs.

Why Use Modules in Python?

Modules provide several advantages:

  • Code reusability – Write once, use multiple times
  • Better organization – Separate logic into manageable files
  • Maintainability – Easier to update and debug
  • Namespace management – Avoid variable name conflicts
  • Access to Python’s standard library – Thousands of built-in utilities

Most real-world Python projects rely heavily on modules.

Types of Modules in Python

Python supports three main types of modules:

1. Built-in Modules

These come pre-installed with Python.

Examples:

  • math
  • sys
  • os
  • random
  • datetime

2. User-Defined Modules

Custom modules created by developers.

Example:

  • math_utils.py
  • data_processing.py

3. Third-Party Modules

Installed using package managers like pip.

Examples:

Basic Syntax for Importing Modules

The simplest way to import a module is:

import module_name

Example: Importing the math Module

import math

print(math.sqrt(25))
print(math.pi)

Output:

5.0
3.141592653589793

Here, math is the module name, and its functions are accessed using dot notation.

Importing Specific Functions from a Module

Instead of importing the entire module, you can import specific components.

Syntax

from module_name import function_name

Example

from math import sqrt, pi

print(sqrt(16))
print(pi)

This approach makes code cleaner but requires careful handling of name conflicts.

Importing All Functions Using the Asterisk (*)

Python allows importing everything from a module using *.

Syntax

from module_name import *

Example

from math import *

print(sqrt(36))
print(factorial(5))

Why This Is Discouraged

  • Pollutes the namespace
  • Makes code harder to read
  • Increases chances of name conflicts

Best practice: Avoid wildcard imports in production code.

Using Aliases While Importing Modules

Aliases allow shorter or more meaningful names.

Syntax

import module_name as alias

Example

import numpy as np

array = np.array([1, 2, 3])
print(array)

Aliases are widely used in professional Python development.

Aliasing Imported Functions

You can also alias individual functions.

Example

from math import factorial as fact

print(fact(6))

This is useful when function names are long or conflict with existing names.

Importing User-Defined Modules

To import your own module, ensure that:

  • The module is in the same directory
  • Or included in the Python path

Example

File structure:

project/
│
├── main.py
└── calculator.py

calculator.py

def multiply(a, b):
    return a * b

main.py

import calculator

print(calculator.multiply(4, 5))

Importing from Subfolders (Packages)

A package is a folder containing modules and an __init__.py file.

Example Folder Structure

project/
│
├── utilities/
│   ├── __init__.py
│   └── string_utils.py
└── main.py

string_utils.py

def to_upper(text):
    return text.upper()

main.py

from utilities.string_utils import to_upper

print(to_upper("python"))

What Is __init__.py?

The __init__.py file tells Python that a directory should be treated as a package.

It can also contain initialization code or expose selected modules.

Example

from .string_utils import to_upper

Understanding Python Module Search Path

When you import a module, Python searches in the following order:

  1. Current directory
  2. PYTHONPATH environment variable
  3. Standard library directories
  4. Site-packages directory

You can inspect the search path using:

import sys
print(sys.path)

The sys Module Example

import sys

print(sys.version)
print(sys.platform)

The sys module provides access to interpreter-level information.

The os Module Example

The os module allows interaction with the operating system.

import os

print(os.getcwd())
print(os.listdir())

Importing Modules Conditionally

Sometimes, you may want to import modules based on conditions.

Example

if True:
    import math

print(math.sqrt(49))

This is useful in platform-specific or optional dependency scenarios.

Dynamic Imports Using importlib

Python allows importing modules dynamically at runtime.

Example

import importlib

math_module = importlib.import_module("math")
print(math_module.pow(2, 3))

Dynamic imports are useful for plugins and extensible systems.

Reloading a Module

If a module is updated during runtime, Python does not reload it automatically.

Example

import importlib
import mymodule

importlib.reload(mymodule)

This is especially helpful during development.

Common Import Errors and How to Fix Them

ModuleNotFoundError

ModuleNotFoundError: No module named 'example'

Fixes:

ImportError

Occurs when a specific function does not exist.

from math import square

Fix: Confirm function availability.

Best Practices for Importing Modules in Python

  • Place imports at the top of the file
  • Use explicit imports instead of wildcard imports
  • Group imports logically:
    • Standard library
    • Third-party modules
    • Local modules
  • Use aliases consistently
  • Avoid circular imports

Circular Import Explained

A circular import occurs when two modules import each other.

Example

# a.py
import b
# b.py
import a

Solution:

  • Refactor code
  • Use function-level imports

Real-World Example: Using Multiple Imports Together

import os
import sys
from math import sqrt
import datetime as dt

print(os.getcwd())
print(sys.version)
print(sqrt(81))
print(dt.datetime.now())

This demonstrates combining different import styles in a single program.

When to Use Which Import Style?

ScenarioRecommended Style
General useimport module
Few functionsfrom module import function
Long module nameAlias
Large projectsExplicit imports
Avoid conflictsModule-based imports

How Imports Improve Code Quality

Well-structured imports lead to:

  • Cleaner architecture
  • Easier debugging
  • Improved collaboration
  • Faster development
  • Scalable applications

Mastering imports is a step toward writing professional-grade Python code.

Conclusion

Importing modules in Python is more than just a syntax feature; it is the foundation of reusable, maintainable, and scalable software development. Whether you are using built-in libraries, third-party packages, or your own custom modules, understanding how imports work helps you write cleaner and more efficient code an essential skill taught in any Best Online Python Course focused on real-world, production-ready Python development.

By learning different import techniques, avoiding common pitfalls, and following best practices, you can significantly improve the quality and structure of your Python programs.

As you progress in Python, you will find that effective module usage is essential for real-world applications, from automation scripts to enterprise-grade systems.

Share this article

Enroll Free demo class
Enroll IT Courses

Enroll Free demo class

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Join Free Demo Class

Let's have a chat