Python: Modules and Packages

77raina·2020년 4월 27일


Assume there is a package name called 'abc'. We need to import package 'abc' to use it.

import abc

In this case, 'abc' would be a simple python file or a directory that contains python files.

Then how does python find the modules and packages?

sys.modules vs. sys.path


  • First place to be checked to find python modules and packages
  • Has a functionality that once python packages and modules get imported, there's no need to find again
  • Newly imported modules cannot be found


  • The last place to be checked
  • Basically a list of strings that show paths


  • Python needs to iterate through the directory paths of list to see if there's a package that is to be imported

sys module location

When finding modules and packages, python checks sys.modules first, if none, checks built in modules, and for the last checks directory path assigned in sys.path. If there's none in overall, it raises an error 'ModuleNotFoundError'.

Absolute Path vs. Relative Path

To import a local package

Absolute Path

Directory path is same all the time regardless of imported file and its path.

└── my_app
       ├── package1
        │          ├──
        │          └──
      └── package2
                   └── subpackage1

  • When package is imported, file codes are automatically executed.
  • What is this for?
    - Reduce the length of path when importing
    - Restrict the variable, function, and class in the package to be imported
    - Besides any codes that need to be exectued primarily when the package is imported

It is a project named 'my app' and has two packages 1 and 2.
Importing package1 and package2 using Absolute path is following.

from package1 import module1
from package1.module2 import function1
from package2 import class1
from package2.subpackage1.module5 import function2

Starting point of the path is the highest point of 'my app' project.
Ex) Importing function2 in module5 in subpackage1 in linux directory path format.


Current directory will be included in sys.path as default. Therefore, absolute path starts from current directory.

One weakness could be its length. Alternative way is relative path.

Relative Path

It defines the path starting from the imported package location, so it is usually used when local package is imported in another local package.

from . import class1
from .subpackage1.module5 import function2

  • one dot: current directory
  • two dots: parent directory

One weakness is that it may create confusion and path location needs to be changed if file location is changed.

I'm wrapping up this post with my example calculator for relative and absolute path.

└── calculator
       ├── package1
        │          ├──
        │          └──

  • Absolute path

    from package1.module1 import add
    from package1.module2 import sub

  • Relative path

    from .module2 import sub

Backend Developer

0개의 댓글