[파이썬] 패키지의 상대 경로 임포트

When working with Python, you often come across situations where you need to import modules or packages from a different directory within your project. One common approach to handle this is by using relative imports.

Relative imports allow you to import modules or packages based on their position relative to the current module. It’s a convenient way to organize and access your code within the project structure.

To illustrate the concept of relative imports, let’s consider a project structure like this:

my_project/
    main.py
    utils/
        __init__.py
        helper.py
    modules/
        __init__.py
        calculator.py

In this example, we have a main module (main.py) at the root level of our project. The utils and modules directories are separate packages containing modules.

To import a module from a different package using relative imports, you can follow these guidelines:

  1. Identify the relationship between the current module and the module/package you want to import. Determine the number of levels up or down the directory structure you need to traverse to reach the desired module/package.

  2. Use the appropriate number of dots (.) to represent the directory jumps in the import statement.

For example, if we want to import the helper module inside the calculator module, we need to go up one level (..) to reach the utils package and then import the helper module.

In calculator.py, the import statement would look like this:

from ..utils.helper import some_function

Similarly, if we want to import the calculator module inside the main module, we need to go down one level (.) to reach the modules package and then import the calculator module.

In main.py, the import statement would look like this:

from modules.calculator import calculate

Using relative imports can help you organize your code and improve modularity within your project. However, it’s important to note that relative imports work specifically within packages and may not be suitable for standalone scripts or modules located outside of a package.

Remember to use relative imports responsibly and consider the overall structure and organization of your project when deciding to use them.

I hope this article helps you understand how to use relative imports in Python to import modules or packages from different directories within your project. Happy coding!