Modules in Python – Types and Examples

Like many other programming languages, Python supports modularity. That is, you can break large code into smaller and more manageable pieces. And through modularity, Python supports code reuse. You can import modules in Python into your programs and reuse the code therein as many times as you want.

Modules in Python

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What are Python Modules?

Modules provide us with a way to share reusable functions.

A module is simply a “Python file” which contains code we can reuse in multiple Python programs. A module may contain functions, classes, lists, etc.

Modules in Python can be of two types:

  • Built-in Modules.
  • User-defined Modules.

1. Built-in Modules in Python

One of the many superpowers of Python is that it comes with a “rich standard library”. This rich standard library contains lots of built-in modules. Hence, it provides a lot of reusable code.

To name a few, Python contains modules like “os”, “sys”, “datetime”, “random”.
You can import and use any of the built-in modules whenever you like in your program. (We’ll look at it shortly.)

2. User-Defined Modules in Python

Another superpower of Python is that it lets you take things in your own hands. You can create your own functions and classes, put them inside modules and voila! You can now include hundreds of lines of code into any program just by writing a simple import statement.

To create a module, just put the code inside a .py file. Let’s create one.

# my Python module

def greeting(x):
    print("Hello,", x)

Write this code in a file and save the file with the name mypymodule.py. Now we have created our own module.

Half of our job is over, now let’s learn how to import these modules.

Importing Modules in Python

We use the import keyword to import both built-in and user-defined modules in Python.

Let’s import our user-defined module from the previous section into our Python shell:

>>> import mypymodule

To call the greeting function of mypymodule, we simply need to use the dot notation:

>>> mypymodule.greeting("Techvidvan")

Output

Hello, Techvidvan

Similarly, we can import mypymodule into any Python file and call the greeting function as we did above.

Let’s now import a built-in module into our Python shell:

>>> import random

To call the randint function of random, we simply need to use the dot notation:

>>> random.randint(20, 100)

Output

63

The randint function of the random module returns a random number between a given range, here (20 to 100).

We can import modules in various different ways to make our code more Pythonic.

Using import…as statement (Renaming a module)

This lets you give a shorter name to a module while using it in your program.

>>> import random as r
>>> r.randint(20, 100)

Output

54

Using from…import statement

You can import a specific function, class, or attribute from a module rather than importing the entire module. Follow the syntax below,

from <modulename> import <function>

>>> from random import randint
>>> randint(20, 100)
69

You can also import multiple attributes and functions from a module:

>>> from math import pi, sqrt
>>> print(3 * pi)
9.42477796076938
>>> print(sqrt(100))
10.0
>>> 

Note that while importing from a module in this way, we don’t need to use the dot operator while calling the function or using the attribute.

Importing everything from Python module

If we need to import everything from a module and we don’t want to use the dot operator, do this:

>>> from math import *
>>> print(3 * pi)
9.42477796076938
>>> print(sqrt(100))
10.0
>>> 

Python dir() function

The dir() function will return the names of all the properties and methods present in a module.

>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> 

Reloading Modules in Python

If you have already imported a module but need to reload it, use the reload() method. This is intended to be used in cases when you edit a source file of a module and need to test it without leaving Python.
In Python 3.0 and above, you need to import imp standard library module to make use of this function.

>>> import random
>>> import imp
>>> imp.reload(random)

Wrapping Up!

This brings us to the end of our article on modules. Modules are a great deal in programming languages as they give us the ability to reuse code in a much more manageable way. They say, “Python comes with batteries included”. By batteries, they mean modules. Modules are everything you need to get going. All you have to do is code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.