What are Modules and Packages in Python?

In modular programming, code is divided into modules to reduce complexity of the system.

palash sharma
2 min readSep 2, 2019

Modules are .py files whereas packages are directories with multiple python scripts. Both can be utilized for code reusability using python “from” and “import” statements.

Modules in Python

Module is a .py file containing python function, class definitions or other python statements.

If you are in the same directory as of the python file. You can use import statement to access objects of the file.

Once imported, your module will be treated as a python object. Following methods can help you while dealing with a custom or predefined module:

  • dir(): returns list of attributes and methods of any object
  • __doc__ attribute: returns the docstring of a python object

Packages

A python package is a directory which might consist sub packages or modules (.py files). Difference between a package and a directory is that a python package must have a __init__.py file.

__init__.py file can be empty or it can be used for code initialization.

A package can have multiple sub-packages and sub-packages can have multiple sub-packages too as well as multiple modules.

A simple analogy can explain more intuitively:

import numpy as np
arr = np.random.randint(10)
  • numpy is a python package.
  • random is a sub package of numpy with __init__.py file.
  • randint is a function which can be found in the file numpy/random/__init__.py

Imports can have following general formats:

import module_name
import module_name as mn # renamed import for convenience
from module_name import method1, method2
import package_name
from package_name import module_name
import package_name.sub_package_name.module_name
from package_name.sub_package_name.module_name import method_name

Thanks!

--

--