Import module or package in Python

Table of Contents

Suppose that a main script of [cci]main.py[/cci] (or a corresponding [cci]Jupyter Notebook[/cci]) exists in the directory of [cci]myproject[/cci], and its subdirectory [cci]sub[/cci] contains modules of [cci]mod_a.py[/cci] (a function of [cci]func_a ()[/cci] included) and [cci]mod_b.py[/cci] (a function of [cci]func_b()[/cci] included) where [cci]main.py[/cci] imports the module [cci]mod_a[/cci] and the module [cci]mod_a[/cci] imports the module [cci]mod_b[/cci]. First, creating an empty file [cci]__init__.py[/cci] in the directory [cci]sub[/cci] so that [cci]sub[/cci] is recognized as a package as shown below:
[cc]
myproject/
main.py
sub/
__init__.py
mod_a.py (func_a())
mod_b.py (func_b())
[/cc]
The sub-directory, [cci]sub[/cci], containing two modules, becomes a package when [cci]__init__.py[/cci] is included.

Import [cci]mod_a.py[/cci] in [cci]main.py[/cci]

The following is how to import the module [cci]mod_a.py[/cci] included in the package [cci]sub[/cci] in [cci]main.py[/cci]:
[cc lang='python']
### myproject/main.py
import sub.mod_a
sub.mod_a.func_a()
[/cc]
Or as follows:
[cc lang='python']
### myproject/main.py
from sub import mod_a
mod_a.func_a()
[/cc]
Or as follows:
[cc lang='python']
### myproject/main.py
from sub.mod_a import func_a
func_a
[/cc]
As seen above, by importing a function remaining after designating in [cci]from[/cci], the function can be called without appending package and module names. If there are other functions or classes in the module, these can be imported by itemizing with comma separator or all the functions and classes under the module can be imported by using asterisk [cci]*[/cci] like [cci]from sub.mod_a import *[/cci]. However, it is safe not to use the asterisk because it is difficult to recognize what functions and classes are imported.

Import module [cci]mod_b[/cci] in module [cci]mod_a[/cci] when both of them exist in the same sub-directory

The following is how to import module [cci]mod_b[/cci] in module [cci]mod_a[/cci] when both of them exit in the same sub-directory (or package):
[cc lang='python']
### myproject/sub/mod_a.py
from . import mod_b
mod_b.func_b()
[/cc]
It is incorrect to [cci]import mod_b[/cci]. Instead of [cci].[/cci], you may use the name of sub-directory [cci]sub[/cci] as follows:
[cc lang='python]
### myproject/sub/mod_a.py
from sub import mod_b
mod_b.func_b()
[/cc]
It is convenient to use dot [cci].[/cci] as the sub-directory name does not matter.

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.