Modules vs Packages vs Libraries in Python

The terms ‘module’, ‘package’ & ‘library’ are defined differently by different programming languages. This may cause some confusion for programmers switching from one language to another.

Here’s how these three terms are used in context of python:

Module:

Simply put, a module in python is a .py file that defines one or more function/classes which you intend to reuse in different codes of your program.

To reuse the functions of a given module you simply need to import the module using:

import <modulename> # to import the entire module

from <modulename> import <classname> # imports a class from a module

As regards the module name, Python treats the file name as the module names.

By default, the name of theĀ  module is stored in the name space as a string type. The module name can be called within the moduleĀ  by calling the global variable __name__.

Package

A Python package refers to a directory of Python module(s). This feature comes in handy for organizing modules of one type at one place. A python package is normally installed in:

/usr/lib/python/site-packages # for linux
C:/Python27/Lib/site-packages/ # for windows

To use the package in a script, you will have to first initialize the package using:

mypackage/__init__.pymypackage/mymodule.py

You can then import the package

import mypackage.mymodule

or

from mypackage.mymodule import myclass

In addition to creating ones own packages, Python is home a large and growing collection of packages (from individual programmers) which is available from the Python Package Index.

Library

Unlike C or C++, the term library does not have any specific contextual meaning in p\Python. When used in Python, a library is used loosely to describe a collection of the core modules.

The term ‘standard library‘ in Python language refers to the collection of exact syntax, token and semantics of the Python language which comes bundled with the core Python distribution.

In Python, the standard library is written in C language and it handles the standard functionalities like file I/O and other core modules that make Python what it is. The python standard library lists down more than 200 such core modules that form the core of Python.

“Additional libraries” refer to those optional components that are commonly included in Python distributions.

The Python installers for the Windows automatically adds the standard library and some additional libraries.

For Unix-like operating systems, the additional library is generally provided as a collection of packages. In Unix Os, one may have to use packaging tools like easyinstall or pip to use these additional libraries.