目次
- 1 1. Introduction
- 2 2. Basic Concepts of import in Python
- 3 3. Basic Usage of Python import
- 4 4. Execution Order and Mechanism of import
- 5 5. Summary
- 6 6. Advanced import techniques
- 7 7. Causes and Solutions for import-related errors
- 8 8. Frequently Asked Questions (FAQ)
- 9 9. Conclusion (What to Learn Next)
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.- Improved code reusability
- By using existing libraries, you don’t have to write code from scratch.
- 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
- 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 moduleimport math
print(math.pi) # 3.141592653589793
print(math.factorial(5)) # 5! = 120
Example: Using the datetime moduleimport 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 functionfrom 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 npimport 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.- Current directory
- Directories specified by the
PYTHONPATH
environment variable - Python’s standard library
site-packages
directory (location for external libraries)
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.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.
6. Advanced import techniques
The Pythonimport
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 importmath_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, theimportlib
module is handy.6.2.1. How to use importlib.import_module()
For example, if you only want to importnumpy
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, writingfrom 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 imported ⚠ Name 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 usingimport
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 messageModuleNotFoundError: No module named 'numpy'
Causenumpy
and other external libraries are not installed- The module path is not included in
sys.path
- The Python virtual environment is different
pip install numpy
✅ Check the packages installed in the current environmentpip list
✅ Activate the virtual environment (for venv)source venv/bin/activate # Mac/Linux
venvScriptsctivate # Windows
✅ Verify the module pathimport 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 messageImportError: cannot import name 'my_function' from 'my_module'
Causemy_module.py
does not definemy_function
- Syntax error in
import
(e.g., trying to import a class instead of a function) - Circular import (see below)
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 messageImportError: cannot import name 'A' from partially initialized module 'B'
Causemodule_a.py
importsmodule_b.py
, andmodule_b.py
also importsmodule_a.py
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. Solution ✅ Move 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
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from module_b import B
8. Frequently Asked Questions (FAQ)
Regarding Python’simport
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 entiremath
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 thesqrt()
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 installedpip install numpy
✅ Verify that the virtual environment is set up correctlysource 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 moduleimport my_module
print(dir(my_module)) # check objects inside my_module
✅ Perform the import inside a function to avoid circular importsdef 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 imported ⚠ Name collisions are more likely ⚠ Unnecessary objects may also get imported Alternativefrom 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’simport
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 ofimport
, 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.