Python Imports Explained: Basics, Advanced Tips & Error Fixes

目次

1. Introduction

When you start learning Python, you will almost certainly encounter import statements. In Python, you can efficiently create programs by leveraging the standard library, external libraries, and even your own modules. This is made possible by the import mechanism. In this article, we will clearly explain everything from the basic usage of “import python” to advanced techniques, common errors, and their solutions, in a way that beginners can understand.

2. Basic Concepts of import in Python

2.1 What is import?

In Python, import is a mechanism for bringing external modules into a program. Python provides many useful standard libraries, and by using import statements to call them, you can develop programs efficiently. For example, if you want to use the math module for mathematical calculations, you would write as follows.
import math
print(math.sqrt(16))  # 4.0
In the above example, the math module is imported, and its sqrt function (which calculates the square root) is used.

2.2 Benefits of Using import

By leveraging Python’s import, you gain the following advantages.
  1. Improved code reusability
  • By using existing libraries, you don’t have to write code from scratch.
  1. Increased development efficiency
  • For example, using the random module makes generating random numbers easy.
  • Example: import random print(random.randint(1, 100)) # outputs a random integer from 1 to 100
  1. Easy extensibility
  • By incorporating external libraries (such as NumPy or Pandas), advanced processing becomes possible.
侍エンジニア塾

3. Basic Usage of Python import

3.1 Importing Standard Libraries

Python includes many standard libraries that are provided out of the box. For example, math and datetime are part of the standard library and can be imported without any additional installation. Example: Using the math module
import math
print(math.pi)  # 3.141592653589793
print(math.factorial(5))  # 5! = 120
Example: Using the datetime module
import datetime
now = datetime.datetime.now()
print(now)  # output the current date and time

3.2 Using from … import …

It is also possible to import only specific functions. Example: Importing only the sqrt function
from math import sqrt
print(sqrt(25))  # 5.0
With this approach, you can use sqrt() directly instead of math.sqrt(), making the code more concise.

3.3 Specifying an Alias for import

If a module name is long, you can set an alias. Example: Importing numpy as np
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)  # [1 2 3 4]
Doing so can improve the readability of your code.

4. Execution Order and Mechanism of import

4.1 Module Search Path

Python searches for imported modules in the following order.
  1. Current directory
  2. Directories specified by the PYTHONPATH environment variable
  3. Python’s standard library
  4. site-packages directory (location for external libraries)
To check the current search path, run the following code.
import sys
print(sys.path)
The printed list shows the directories Python searches for modules.

4.2 Adding Paths Using sys.path.append()

When importing a custom module, adding its location to the search path makes it importable.
import sys
sys.path.append('/path/to/custom/module')
import my_module  # import custom module

4.3 Role of __init__.py

In Python, if a directory contains a __init__.py, it is recognized as a package. This allows you to import submodules.
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

5. Summary

  • By using import statements, you can leverage Python’s standard library and external libraries.
  • You can import standard modules, such as import math.
  • Using from module import function lets you import only a specific function.
  • Aliases (e.g., import numpy as np) let you shorten long module names.
  • Understanding the search path is key to avoiding import errors.
In the next article, we will discuss advanced import techniques in Python (relative imports, dynamic imports, etc.). Use this knowledge to start writing more practical Python programs! 🚀

6. Advanced import techniques

The Python import statement can be used not only in its basic form but also with advanced techniques depending on the situation. Here, we will discuss in detail the relative imports, dynamic imports, and the risks of wildcard imports.

6.1. Relative imports and absolute imports

In Python, there are two ways to import modules: “absolute import” and “relative import”.

6.1.1. Absolute import

Absolute import refers to importing a module by specifying a path from the root directory (the top level of the project).
# Example project structure
my_project/
│── main.py
│── utils/
│   ├── helper.py
│   └── math_utils.py
To import math_utils.py from main.py, you would use an absolute import as follows.
# main.py
import utils.math_utils  # absolute import

6.1.2. Relative import

Relative import means importing a module by specifying its location relative to the current directory or a parent directory. For example, to import math_utils.py from helper.py, you can write:
# helper.py
from . import math_utils  # import module from the same directory
from .. import another_module  # import module from the parent directory

6.2. Dynamic imports using importlib

Normally, Python evaluates import statements once at program startup. However, there are cases where you want to determine which module to import at runtime. In such cases, the importlib module is handy.

6.2.1. How to use importlib.import_module()

For example, if you only want to import numpy when it is installed, you can dynamically import it using importlib.import_module().
import importlib

module_name = "math"
math_module = importlib.import_module(module_name)

print(math_module.sqrt(25))  # 5.0

6.3. Risks of import * (wildcard import)

In Python, writing from module import * imports all functions and variables from the module.
from math import *
print(sqrt(16))  # 4.0

6.3.1. Why you should avoid wildcard imports

It’s hard to tell which variables or functions were importedName collisions are more likely (when different modules have functions with the same name) ⚠ Performance can degrade (unnecessary variables may be imported) Alternatives
  • Import only the functions you need explicitly
  from math import sqrt, pi
  • Use an alias to make it clear
  import numpy as np

7. Causes and Solutions for import-related errors

When using import in Python, beginners often encounter several errors. This section provides a detailed explanation of the types and causes of import errors, and the corresponding solutions.

7.1. ModuleNotFoundError: No module named 'xxx'

Error message
ModuleNotFoundError: No module named 'numpy'
Cause
  • numpy and other external libraries are not installed
  • The module path is not included in sys.path
  • The Python virtual environment is different
SolutionsInstall the required modules
pip install numpy
Check the packages installed in the current environment
pip list
Activate the virtual environment (for venv)
source venv/bin/activate  # Mac/Linux
venvScriptsctivate  # Windows
Verify the module path
import sys
print(sys.path)
If the desired module cannot be found, you can add it using sys.path.append('path').

7.2. ImportError: cannot import name 'xxx'

Error message
ImportError: cannot import name 'my_function' from 'my_module'
Cause
  • my_module.py does not define my_function
  • Syntax error in import (e.g., trying to import a class instead of a function)
  • Circular import (see below)
SolutionCheck the target module Check that my_function is correctly defined in my_module.py. ✅ Correct the incorrect import statement
# Mistake
from my_module import my_function

# Fix
import my_module
print(my_module.my_function())
Check for possible circular imports Refer to the 7.3 section below.

7.3. Circular import (Circular Import)

Error message
ImportError: cannot import name 'A' from partially initialized module 'B'
Cause
  • module_a.py imports module_b.py, and module_b.py also imports module_a.py
Example: code that causes a circular import module_a.py
from module_b import B
class A:
    pass
module_b.py
from module_a import A
class B:
    pass
When you run module_a.py in this state, a circular import error occurs. SolutionMove the import inside a function
# module_a.py
def use_module_b():
    from module_b import B
    b_instance = B()
Reevaluate module dependencies
  • Design to reduce dependencies as much as possible
  • Design so that a single module does not have multiple responsibilities
Use delayed (lazy) imports
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from module_b import B

8. Frequently Asked Questions (FAQ)

Regarding Python’s import statements, we explain the points that beginners to intermediate users often wonder about in a Q&A format. We introduce common issues and their solutions, incorporating real error messages and concrete examples.

8.1. What is the difference between import and from ... import ...?

A: import and from ... import ... are both ways to use modules, but they behave differently.

1. When using import

import math
print(math.sqrt(16))  # 4.0
  • When you run import math, the entire math module is imported.
  • You need to specify the module name to call functions (e.g., math.sqrt(16)).

2. When using from ... import ...

from math import sqrt
print(sqrt(16))  # 4.0
  • When you run from math import sqrt, only the sqrt() function is imported.
  • Because you can call the function directly without the module name, the code becomes more concise.

8.2. How to handle ModuleNotFoundError: No module named 'xxx'?

Check that the module is installed
pip install numpy
Verify that the virtual environment is set up correctly
source venv/bin/activate  # Mac/Linux
venv\Scripts\activate  # Windows

8.3. Why does ImportError: cannot import name 'xxx' occur?

Check that the function or class exists in the module
import my_module
print(dir(my_module))  # check objects inside my_module
Perform the import inside a function to avoid circular imports
def use_module_b():
    from module_b import some_class

8.4. Is it okay to use import *?

A: It should generally be avoided. ⚠ It’s hard to tell which functions or variables were importedName collisions are more likelyUnnecessary objects may also get imported Alternative
from math import sqrt, pi

8.5. How to reload an imported module?

Use importlib.reload()
import importlib
import my_module

importlib.reload(my_module)

9. Conclusion (What to Learn Next)

By understanding Python’s import statement, you have learned how to effectively use modules and libraries. This article provided a detailed explanation, covering everything from basic import usage to advanced techniques, common errors, and their solutions. In Python programming, understanding how import works is an essential skill that improves code readability and development efficiency. Use the knowledge you gained here to further expand your use of Python.

9.1. What to Learn Next

Once you’ve mastered the basics of import, the following topics are recommended for your next study.

1. Python Package Management (pip & venv)

In Python, managing external libraries is extremely important. To make the most of import, you should learn how to install libraries using pip and set up virtual environments (venv).
pip install requests  # Install library
python -m venv myenv  # Create virtual environment
source myenv/bin/activate  # Activate virtual environment (Mac/Linux)
myenvScriptsactivate  # Activate virtual environment (Windows)

2. Python Object-Oriented Programming (Classes and Methods)

After you can split modules using import, the next recommended step is to learn Python’s object-oriented programming (OOP).
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "..."

class Dog(Animal):
    def speak(self):
        return "Woof"

my_dog = Dog("Pochi")
print(my_dog.speak())  # Woof

3. Python Parallel Processing and Multithreading

If you want to tackle more advanced Python programming, learning to use parallel processing and multithreading is beneficial.
import threading

def print_numbers():
    for i in range(5):
        print(i)

thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()

9.2. Summary

  • By leveraging Python’s import, you can effectively use standard and external libraries.
  • Understanding how import works makes code modularization and reuse easier.
  • As the next step, learning package management, object-oriented programming, and parallel processing will enhance your skills.
  • It’s important to advance your learning practically while using official documentation and learning resources.
This completes the comprehensive guide on “import python”! 🎉 Use this knowledge to take on more advanced Python programming! 🚀
年収訴求