What are Modules in Python?

Subscribe to my newsletter and never miss my upcoming articles

Modules are pieces of code that others have written to fulfill common tasks, such as performing mathematical operations. A good example is math module, which you can import as follows:

import math
print(math.sqrt(25)) #sqrt means "square root"

Another kind of import that can be used if you only need certain functions from a module is: from module_name import needed_function. For example, to import only the pi constant from the math module:

from math import pi

If you add a comma, then you can import two or more functions:

from math import pi, sqrt

Trying to import a module that isn't available causes an ImportError.

Moreover, * imports all objects from a module, as in from math import *. But this is a bad practice, as it confuses variables in your code with variables in the external module.

Types of modules

There are three main types of modules in Python:

  1. The ones you write yourself.

  2. Those you install from external sources. Many third-party Python modules are stored on the Python Package Index (PyPI). The best way to install these is using a program called pip. This comes installed by default with modern distributions of Python. If you don't have it, it is easy to install online. Once you have it, look up the name of the library you want to install, go to the command line, and enter pip install library_name.

  3. Those that are preinstalled with Python (called the standard library**.)

Some of the standard library's useful modules include string, re, datetime, math, random, os, multiprocessing, subprocess, socket, email, json, doctest, unittest, pdb, argparse and sys.

Tasks that can be done by the standard library include string parsing, data serialization, testing, debugging and manipulating dates, emails, and much more.

Using pip is the standard way of installing libraries on most OS, but some libraries offer normal executable files that let you install libraries with a GUI (graphical user interface), the same way you would install other programs.

Source: SoloLearn