Python Modules

In this article, you will learn to create and import custom modules in Python. Also, you will find different techniques to import and use custom and built-in modules in Python.

1. What are modules in Python?

Modules refer to a file containing Python statements and definitions.

A file containing Python code, for example: example.py, is called a module, and its module name would be example.

We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code.

We can define our most used functions in a module and import it, instead of copying their definitions into different programs.

Let us create a module. Type the following and save it as example.py.

# Python Module example

def add(a, b):
   """This program adds two
   numbers and return the result"""

   result = a + b
   return result

Here, we have defined a function add() inside a module named example. The function takes in two numbers and returns their sum.


2. How to import modules in Python?

We can import the definitions inside a module to another module or the interactive interpreter in Python.

We use the import keyword to do this. To import our previously defined module example, we type the following in the Python prompt.

>>> import example

This does not import the names of the functions defined in example directly in the current symbol table. It only imports the module name example there.

Using the module name we can access the function using the dot . operator. For example:

>>> example.add(4,5.5)
9.5

Python has tons of standard modules. You can check out the full list of Python standard modules and their use cases. These files are in the Lib directory inside the location where you installed Python.

Standard modules can be imported the same way as we import our user-defined modules.

There are various ways to import modules. They are listed below..


2.1. Python import statement

We can import a module using the import statement and access the definitions inside it using the dot operator as described above. Here is an example.

# import statement example
# to import standard module math

import math
print("The value of pi is", math.pi)

When you run the program, the output will be:

The value of pi is 3.141592653589793

2.2. Import with renaming

We can import a module by renaming it as follows:

# import module by renaming it

import math as m
print("The value of pi is", m.pi)

We have renamed the math module as m. This can save us typing time in some cases.

Note that the name math is not recognized in our scope. Hence, math.pi is invalid, and m.pi is the correct implementation.

2.3. Python from…import statement

We can import specific names from a module without importing the module as a whole. Here is an example.

# import only pi from math module

from math import pi
print("The value of pi is", pi)

Here, we imported only the pi attribute from the math module.

In such cases, we don’t use the dot operator. We can also import multiple attributes as follows:

>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045

2.4. Import all names

We can import all names(definitions) from a module using the following construct:

# import all names from the standard module math

from math import *
print("The value of pi is", pi)

Here, we have imported all the definitions from the math module. This includes all names visible in our scope except those beginning with an underscore(private definitions).

Importing everything with the asterisk (*) symbol is not a good programming practice. This can lead to duplicate definitions for an identifier. It also hampers the readability of our code.

While importing a module, Python looks at several places. Interpreter first looks for a built-in module. Then(if built-in module not found), Python looks into a list of directories defined in sys.path. The search is in this order.

  • The current directory.
  • PYTHONPATH (an environment variable with a list of directories).
  • The installation-dependent default directory.
>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']

We can add and modify this list to add our own path.


4. Reloading a module

The Python interpreter imports a module only once during a session. This makes things more efficient. Here is an example to show how this works.

Suppose we have the following code in a module named my_module.

# This module shows the effect of
#  multiple imports and reload

print("This code got executed")

Now we see the effect of multiple imports.

>>> import my_module
This code got executed
>>> import my_module
>>> import my_module

We can see that our code got executed only once. This goes to say that our module was imported only once.

Now if our module changed during the course of the program, we would have to reload it.One way to do this is to restart the interpreter. But this does not help much.

Python provides a more efficient way of doing this. We can use the reload() function inside the imp module to reload a module. We can do it in the following ways:

>>> import imp
>>> import my_module
This code got executed
>>> import my_module
>>> imp.reload(my_module)
This code got executed
<module 'my_module' from '.\\my_module.py'>

5. The dir() built-in function

We can use the dir() function to find out names that are defined inside a module.

For example, we have defined a function add() in the module example that we had in the beginning.

We can use dir in example module in the following way:

>>> dir(example)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__initializing__',
'__loader__',
'__name__',
'__package__',
'add']

Here, we can see a sorted list of names (along with add). All other names that begin with an underscore are default Python attributes associated with the module (not user-defined).

For example, the __name__ attribute contains the name of the module.

>>> import example
>>> example.__name__
'example'

All the names defined in our current namespace can be found out using the dir() function without any arguments.

>>> a = 1
>>> b = "hello"
>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'math', 'pyscripter']

6. Python Random Module

You can generate random numbers in Python by using random module.

Python offers random module that can generate random numbers.

These are pseudo-random number as the sequence of number generated depends on the seed.

If the seeding value is same, the sequence will be the same. For example, if you use 2 as the seeding value, you will always see the following sequence.

import random
random.seed(2)

print(random.random())
print(random.random())
print(random.random())

The output will always follow the sequence:

0.9560342718892494
0.9478274870593494
0.05655136772680869

Not so random eh? Since this generator is completely deterministic, it must not be used for encryption purpose.

Here is the list of all the functions defined in random module with a brief explanation of what they do.

FunctionDescription
seed(a=None, version=2)Initialize the random number generator
getstate()Returns an object capturing the current internal state of the generator
setstate(state)Restores the internal state of the generator
getrandbits(k)Returns a Python integer with k random bits
randrange(start, stop[, step])Returns a random integer from the range
randint(a, b)Returns a random integer between a and b inclusive
choice(seq)Return a random element from the non-empty sequence
shuffle(seq)Shuffle the sequence
sample(population, k)Return a k length list of unique elements chosen from the population sequence
random()Return the next random floating point number in the range [0.0, 1.0)
uniform(a, b)Return a random floating point number between a and b inclusive
triangular(low, high, mode)Return a random floating point number between low and high, with the specified mode between those bounds
betavariate(alpha, beta)Beta distribution
expovariate(lambd)Exponential distribution
gammavariate(alpha, beta)Gamma distribution
gauss(mu, sigma)Gaussian distribution
lognormvariate(mu, sigma)Log normal distribution
normalvariate(mu, sigma)Normal distribution
vonmisesvariate(mu, kappa)Vonmises distribution
paretovariate(alpha)Pareto distribution
weibullvariate(alpha, beta)Weibull distribution

Visit this page to learn more on how you can generate pseudo-random numbers in Python.

7. Python Mathematical Functions

Learn about all the mathematical functions available in Python and how you can use them in your program.

7.1. What is math module in Python?

The math module is a standard module in Python and is always available. To use mathematical functions under this module, you have to import the module using import math.

It gives access to the underlying C library functions. For example,

# Square root calculation

import math
math.sqrt(4)

This module does not support complex datatypes. The cmath module is the complex counterpart.

7.2. Functions in Python Math Module

Here is the list of all the functions and attributes defined in math module with a brief explanation of what they do.

FunctionDescription
ceil(x)Returns the smallest integer greater than or equal to x.
copysign(x, y)Returns x with the sign of y
fabs(x)Returns the absolute value of x
factorial(x)Returns the factorial of x
floor(x)Returns the largest integer less than or equal to x
fmod(x, y)Returns the remainder when x is divided by y
frexp(x)Returns the mantissa and exponent of x as the pair (m, e)
fsum(iterable)Returns an accurate floating point sum of values in the iterable
isfinite(x)Returns True if x is neither an infinity nor a NaN (Not a Number)
isinf(x)Returns True if x is a positive or negative infinity
isnan(x)Returns True if x is a NaN
ldexp(x, i)Returns x * (2**i)
modf(x)Returns the fractional and integer parts of x
trunc(x)Returns the truncated integer value of x
exp(x)Returns e**x
expm1(x)Returns e**x – 1
log(x[, b])Returns the logarithm of x to the base b (defaults to e)
log1p(x)Returns the natural logarithm of 1+x
log2(x)Returns the base-2 logarithm of x
log10(x)Returns the base-10 logarithm of x
pow(x, y)Returns x raised to the power y
sqrt(x)Returns the square root of x
acos(x)Returns the arc cosine of x
asin(x)Returns the arc sine of x
atan(x)Returns the arc tangent of x
atan2(y, x)Returns atan(y / x)
cos(x)Returns the cosine of x
hypot(x, y)Returns the Euclidean norm, sqrt(x*x + y*y)
sin(x)Returns the sine of x
tan(x)Returns the tangent of x
degrees(x)Converts angle x from radians to degrees
radians(x)Converts angle x from degrees to radians
acosh(x)Returns the inverse hyperbolic cosine of x
asinh(x)Returns the inverse hyperbolic sine of x
atanh(x)Returns the inverse hyperbolic tangent of x
cosh(x)Returns the hyperbolic cosine of x
sinh(x)Returns the hyperbolic cosine of x
tanh(x)Returns the hyperbolic tangent of x
erf(x)Returns the error function at x
erfc(x)Returns the complementary error function at x
gamma(x)Returns the Gamma function at x
lgamma(x)Returns the natural logarithm of the absolute value of the Gamma function at x
piMathematical constant, the ratio of circumference of a circle to it’s diameter (3.14159…)
emathematical constant e (2.71828…)

Visit this page to learn about all the mathematical functions defined in Python 3.

4 Trackbacks / Pingbacks

  1. Python Program to Display Calendar - VietMX's Blog
  2. Python Program to Safely Create a Nested Directory - VietMX's Blog
  3. Python help() - VietMX's Blog
  4. Python __import__() - VietMX's Blog

Comments are closed.