Python Modules

  • Python

A module in python is a program containing a set of statements or functions that can be used in another python program.

For example, name.py is a module and this can be called by name in other python programs. We do this by using import keyword.

Modules are used to make the python code more flexible and usable which helps in debugging when we hit a bug. So, instead of duplicating the same code, it is easier to import them as modules.

How to import modules in Python?

As mentioned above, we use import to perform this action. Let’s understand this using an example.

def add(a,b):
  return a+b

def sub(a,b):
  return a-b

def mul(a,b):
return a*b

In the above code, we created three functions to add, subtract, and multiply two numbers. Let’s save the above code as code.py. Now to import this module, we’ll create a new python program and will import it.

import code

a = 2
b = 5

c = code.add(a,b)
print(c)

d = code.sub(a,b)
print(d)

Output :

7
-3

In order to call the functions we need to use the above format.

If you want to import only the add() function, we’ll use from keyword and then the format to use the function will also change. You’ll no longer need to write the module name in front.

from code import add

a = 2
b = 5

c = add(a,b)
print(c)

Output :

7

You can also import all the functions instead if need be using asterisk *. Let’s see the below example.

from code import *

a = 2
b = 5

c = add(a,b)
print(c)

d = mul(a,b)
print(d)

Output :

7
10

Can we Rename a Module?

Yes, we can give the module a name of your choice. This can be done using as keyword.

import code as c

a = 2
b = 5

result = c.add(a,b)

Built-in Modules

Python has several built-in modules that you can use. Let’s import one of them and play with the code.

import math

x = math.pi
print(x)

y = math.pow(2,3)
print(y)

z = math.sqrt(96)
print(z)

Output :

3.141592653589793
8.0
9.797958971132712

The dir() function

This is one of the built-in functions that returns a list of functions names defined inside the function. Let’s use the same math module to understand this.

import math

x = dir(math)
print(x)

Output :

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

This is not just used on the built-in modules but can be used on all the modules.