What is a Module?
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
What is Python Module
A Python module is a file containing Python definitions and statements. A module
can define functions, classes, and variables. A module can also include runnable
code. Grouping related code into a module makes the code easier to understand
and use. It also makes the code logically organized.
Create a simple Python module
Let’s create a simple calc.py in which we define two functions, one add and
another subtract.
# A simple module, calc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Import Module in Python
We can import the functions, and classes defined in a module to another module
using the import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if the
module is present in the search path. A search path is a list of directories that the
interpreter searches for importing a module. For example, to import the module
calc.py, we need to put the following command at the top of the script.
Syntax of Python Import
import module
Note: This does not import the functions or classes directly instead imports the
module only. To access the functions inside the module the dot(.) operator is
used.
Importing modules in Python
Now, we are importing the calc that we created earlier to perform add operation.
# importing module calc.py
import calc
print(calc.add(10, 2))
Output:
12
The from-import Statement in Python
Python’s from statement lets you import specific attributes from a module without
importing the module as a whole.
Importing specific attributes from the module
Here, we are importing specific sqrt and factorial attributes from the math module.
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial
# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
Output:
4.0
720
Import all Names
The * symbol used with the from import statement is used to import all the names
from a module to a current namespace.
Syntax:
from module_name import *
From import * Statement
The use of * has its advantages and disadvantages. If you know exactly what you
will be needing from the module, it is not recommended to use *, else do so.
# importing sqrt() and factorial from the
# module math
from math import *
# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
Output
4.0
720
Renaming the Python module
We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
# importing sqrt() and factorial from the
# module math
import math as mt
# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(mt.sqrt(16))
print(mt.factorial(6))
Output
4.0
720
Python built-in modules
There are several built-in modules in Python, which you can import whenever you
like.
# importing built-in module math
import math
# using square root(sqrt) function contained
# in math module
print(math.sqrt(25))
# using pi function contained in math module
print(math.pi)
# 2 radians = 114.59 degrees
print(math.degrees(2))
# 60 degrees = 1.04 radians
print(math.radians(60))
# Sine of 2 radians
print(math.sin(2))
# Cosine of 0.5 radians
print(math.cos(0.5))
# Tangent of 0.23 radians
print(math.tan(0.23))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
# importing built in module random
import random
# printing random integer between 0 and 5
print(random.randint(0, 5))
# print random floating point number between 0 and 1
print(random.random())
# random number between 0 and 100
print(random.random() * 100)
List = [1, 4, True, 800, "python", 27, "hello"]
# using choice function in random module for choosing
# a random element from a set such as a list
print(random.choice(List))
# importing built in module datetime
import datetime
from datetime import date
import time
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print(time.time())
# Converts a number of seconds to a date object
print(date.fromtimestamp(454554))
Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
Python sys module
The python sys module provides functions and variables which are used to manipulate
different parts of the Python Runtime Environment. It lets us access system-specific
parameters and functions.
import sys
First, we have to import the sys module in our program before running any functions.
sys.modules
69.1M
1.2K
Difference between JDK, JRE, and JVM
This function provides the name of the existing python modules which have been
imported.
sys.argv
This function returns a list of command line arguments passed to a Python script. The
name of the script is always the item at index 0, and the rest of the arguments are stored
at subsequent indices.
sys.base_exec_prefix
This function provides an efficient way to the same value as exec_prefix. If not running a
virtual environment, the value will remain the same.
sys.base_prefix
It is set up during Python startup, before site.py is run, to the same value as prefix.
sys.byteorder
It is an indication of the native byteorder that provides an efficient way to do something.
sys.maxsize
This function returns the largest integer of a variable.
sys.path
This function shows the PYTHONPATH set in the current system. It is an environment
variable that is a search path for all the python modules.
sys.stdin
It is an object that contains the original values of stdin at the start of the program and
used during finalization. It can restore the files.
sys.getrefcount
This function returns the reference count of an object.
sys.exit
This function is used to exit from either the Python console or command prompt, and also
used to exit from the program in case of an exception.
sys executable
The value of this function is the absolute path to a Python interpreter. It is useful for
knowing where python is installed on someone else machine.
sys.platform
This value of this function is used to identify the platform on which we are working.
Locating Python Modules
Whenever a module is imported in Python the interpreter looks for several
locations. First, it will check for the built-in module, if not found then it looks for a
list of directories defined in the sys.path. Python interpreter searches for the
module in the following manner –
• First, it searches for the module in the current directory.
• If the module isn’t found in the current directory, Python then searches
each directory in the shell variable PYTHONPATH. The
PYTHONPATH is an environment variable, consisting of a list of
directories.
• If that also fails python checks the installation-dependent list of
directories configured at the time Python is installed.
Directories List for Modules
Here, sys.path is a built-in variable within the sys module. It contains a list of
directories that the interpreter will search for the required module.
# importing sys module
import sys
# importing sys.path
print(sys.path)
Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’,
‘/usr/lib/python3.8/lib-dynload’, ”, ‘/home/nikhil/.local/lib/python3.8/site-
packages’, ‘/usr/local/lib/python3.8/dist-packages’, ‘/usr/lib/python3/dist-
packages’, ‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’,
‘/home/nikhil/.ipython’]
The sys module in Python provides various functions and variables that are
used to manipulate different parts of the Python runtime environment. It allows
operating on the interpreter as it provides access to the variables and functions
that interact strongly with the interpreter. Let’s consider the below example.
Example:
• Python3
import sys
print(sys.version)
Output:
3.6.9 (default, Oct 8 2020, 12:12:24)
[GCC 8.4.0]
In the above example, sys.version is used which returns a string containing the
version of Python Interpreter with some additional information. This shows how
the sys module interacts with the interpreter. Let us dive into the article to get
more information about the sys module.
Input and Output using sys
The sys modules provide variables for better control over input or output. We can
even redirect the input and output to other devices. This can be done using three
variables –
• stdin
• stdout
• stderr
stdin: It can be used to get input from the command line directly. It is used for
standard input. It internally calls the input() method. It, also, automatically adds
‘\n’ after each sentence.
Example:
• Python3
import sys
for line in sys.stdin:
if 'q' == line.rstrip():
break
print(f'Input : {line}')
print("Exit")
Output:
stdout: A built-in file object that is analogous to the interpreter’s standard output
stream in Python. stdout is used to display output directly to the screen console.
Output can be of any form, it can be output from a print statement, an expression
statement, and even a prompt direct for input. By default, streams are in text
mode. In fact, wherever a print function is called within the code, it is first written
to sys.stdout and then finally on to the screen.
Example:
import sys
sys.stdout.write('Geeks')
Output
Geeks
stderr: Whenever an exception occurs in Python it is written to sys.stderr.
Example:
import sys
def print_to_stderr(*a):
# Here a is the array holding the objects
# passed as the argument of the function
print(*a, file = sys.stderr)
print_to_stderr("Hello World")
Output:
Command Line Arguments
Command-line arguments are those which are passed during the calling of the
program along with the calling statement. To achieve this using the sys module,
the sys module provides a variable called sys.argv. It’s main purpose are:
• It is a list of command-line arguments.
• len(sys.argv) provides the number of command-line arguments.
• sys.argv[0] is the name of the current Python script.
Example: Consider a program for adding numbers and the numbers are passed
along with the calling statement.
# Python program to demonstrate
# command line arguments
import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("\nName of Python script:", sys.argv[0])
print("\nArguments passed:", end = " ")
for i in range(1, n):
print(sys.argv[i], end = " ")
# Addition of numbers
Sum = 0
for i in range(1, n):
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)
Output:
Exiting the Program
sys.exit([arg]) can be used to exit the program. The optional argument arg can
be an integer giving the exit or another type of object. If it is an integer, zero is
considered “successful termination”.
Note: A string can also be passed to the sys.exit() method.
Example:
# Python program to demonstrate
# sys.exit()
import sys
age = 17
if age < 18:
# exits the program
sys.exit("Age less than 18")
else:
print("Age is not less than 18")
Output:
An exception has occurred, use %tb to see the full traceback.
SystemExit: Age less than 18
Working with Modules
sys.path is a built-in variable within the sys module that returns the list of
directories that the interpreter will search for the required module.
When a module is imported within a Python file, the interpreter first searches for
the specified module among its built-in modules. If not found it looks through the
list of directories defined by sys.path.
Note: sys.path is an ordinary list and can be manipulated.
Example 1: Listing out all the paths
import sys
print(sys.path)
Output:
Example 2: Truncating the value of sys.path
import sys
# Removing the values
sys.path = []
# importing pandas after removing
# values
import pandas
Output:
ModuleNotFoundError: No module named 'pandas'
sys.modules return the name of the Python modules that the current shell has
imported.
Example:
import sys
print(sys.modules)
Output:
Reference Count
sys.getrefcount() method is used to get the reference count for any given object.
This value is used by Python as when this value becomes 0, the memory for that
particular value is deleted.
Example:
• Python3
import sys
a = 'Geeks'
print(sys.getrefcount(a))
Output
4
More Functions in Python sys
Function Description
sys.setrecursionlimit() method is used to set the maximum
sys.setrecursionlimit() depth of the Python interpreter stack to the required limit.
sys.getrecursionlimit() method is used to find the current
sys.getrecursionlimit() recursion limit of the interpreter or to find the maximum
method depth of the Python interpreter stack.
It is used for implementing debuggers, profilers and
coverage tools. This is thread-specific and must register the
trace using threading.settrace(). On a higher level,
sys.settrace() sys.settrace() registers the traceback to the Python interpreter
sys.setswitchinterval() sys.setswitchinterval() method is used to set the interpreter’s
method thread switch interval (in seconds).
It fetches the largest value a variable of data type Py_ssize_t
sys.maxsize() can store.
maxint/INT_MAX denotes the highest value that can be
sys.maxint represented by an integer.
sys.getdefaultencoding() sys.getdefaultencoding() method is used to get the current
method default string encoding used by the Unicode implementation.
As the name suggests Python time module allows to work with time in Python. It
allows functionality like getting the current time, pausing the Program from
executing, etc. So before starting with this module we need to import it.
Importing time module
The time module comes with Python’s standard utility module, so there is no need
to install it externally. We can simply import it using the import statement.
import time
What is epoch?
The epoch is the point where the time starts and is platform-dependent. On
Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC),
and leap seconds are not counted towards the time in seconds since the epoch.
To check what the epoch is on a given platform we can use time.gmtime(0).
Example: Getting epoch
• Python3
import time
print(time.gmtime(0))
Output:
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0,
tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
From the above example, you can see that epoch is 1 January 1970. This means
that 2 January 1970 can be expressed as 86400 seconds since epoch as there
are 86400 seconds in a day.
Note: The time before the epoch can still be represented in seconds but it will be
negative. For example, 31 December 1969 will be represented as -86400
seconds.
Getting current time in seconds since epoch
time.time() methods return the current time in seconds since epoch. It returns a
floating-point number.
Example: Current time in seconds since epoch
• Python3
import time
curr = time.time()
print("Current time in seconds since epoch =", curr)
Output
Current time in seconds since epoch = 1627908387.764925
Getting time string from seconds
time.ctime() function returns a 24 character time string but takes seconds as
argument and computes time till mentioned seconds. If no argument is passed,
time is calculated till the present.
Example: Getting time string from seconds
• Python3
import time
# getting current time by passing
# the number of seconds since epoch
curr = time.ctime(1627908313.717886)
print("Current time:", curr)
Output
Current time: Mon Aug 2 12:45:13 2021
Delaying Execution of programs
Execution can be delayed using time.sleep() method. This method is used to halt
the program execution for the time specified in the arguments.
Example: Delaying execution time of programs in Python.
• Python3
import time
for i in range(4):
# using sleep() to halt execution
time.sleep(1)
print(i)
Output
0
1
2
3
time.struct_time Class
Struct_time class helps to access local time i.e. non-epochal timestamps. It
returns a named tuple whose value can be accessed by both index and attribute
name. Its object contains the following attributes –
Index Attribute Name Values
0 tm_year 0000, …, 9999
1 tm_mon 1, 2, …, 11, 12
2 tm_mday 1, 2, …, 30, 31
3 tm_hour 0, 1, …, 22, 23
4 tm_min 0, 1, …, 58, 59
5 tm_sec 0, 1, …, 60, 61
6 tm_wday 0, 1, …, 6; Sunday is 6
7 tm_yday 1, 2, …, 365, 366
8 tm_isdst 0, 1 or -1
This class contains various functions. Let’s discuss each function in detail.
time.localtime() method
localtime() method returns the struct_time object in local time. It takes the number
of seconds passed since epoch as an argument. If the seconds parameter is not
given then the current time returned by time.time() method is used.
Example: Getting local time from epoch
• Python3
# importing time module
import time
# Convert the current time in seconds
# since the epoch to a
# time.struct_time object in Local time
obj = time.localtime(1627987508.6496193)
print(obj)
Output
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=16,
tm_min=15, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=0)
time.mktime() method
time.mktime() is the inverse function of time.localtime() which converts the time
expressed in seconds since the epoch to a time.struct_time object in local time.
Example: Converting the struct_time object to seconds since epoch
• Python3
# importing time module
import time
obj1 = time.gmtime(1627987508.6496193)
# Convert the time.struct_time
# object to local time expressed in
# seconds since the epoch
# using time.mktime() method
time_sec = time.mktime(obj1)
# Print the local time in seconds
print("Local time (in seconds):", time_sec)
Output
Local time (in seconds): 1627987508.0
time.gmtime() method
time.gmtime() is used to convert a time expressed in seconds since the epoch to
a time.struct_time object in UTC in which tm_isdst attribute is always 0. If the
seconds parameter is not given then the current time returned by time.time()
method is used.
Example: Use of time.gmtime() method
• Python3
# importing time module
import time
# Convert the current time in seconds
# since the epoch to a
# time.struct_time object in UTC
obj = time.gmtime(1627987508.6496193)
# Print the time.struct.time object
print(obj)
Output
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=10,
tm_min=45, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=0)
time.strftime() method
time.strftime() function converts a tuple or struct_time representing a time as
returned by gmtime() or localtime() to a string as specified by the format
argument. If t is not provided, the current time as returned by localtime() is
used. The format must be a string. ValueError is raised if any field in t is outside
of the allowed range.
Example: Converting struct_time object to a string using strftime() method
• Python3
from time import gmtime, strftime
# using simple format of showing time
s = strftime("%a, %d %b %Y %H:%M:%S",
gmtime(1627987508.6496193))
print(s)
Output
Tue, 03 Aug 2021 10:45:08
time.asctime() method
time.asctime() method is used to convert a tuple or a time.struct_time object
representing a time as returned by time.gmtime() or time.localtime() method to
a string of the following form:
Day Mon Date Hour:Min:Sec Year
Example: Converting tuple to time.struct_time object to string
• Python3
# importing time module
import time
obj = time.gmtime(1627987508.6496193)
# Convert the time.struct_time
# object to a string of the
# form 'Day Mon Date Hour:Min:Sec Year'
# using time.asctime() method
time_str = time.asctime(obj)
print(time_str)
obj = time.localtime(1627987508.6496193)
# Convert the time.struct_time
# object to a string of the
# form 'Day Mon Date Hour:Min:Sec Year'
# using time.asctime() method
time_str = time.asctime(obj)
print(time_str)
Output
Tue Aug 3 10:45:08 2021
Tue Aug 3 10:45:08 2021
time.strptime() method
time.strptime() method converts the string representing time to the struct_time
object.
Example: Converting string to struct_time object.
• Python3
import time
string = "Tue, 03 Aug 2021 10:45:08"
obj = time.strptime(string, "%a, %d %b %Y %H:%M:%S")
print(obj)
Output
time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=10,
tm_min=45, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=-1)
dir() is a powerful inbuilt function in Python3, which returns list of the attributes
and methods of any object (say functions , modules, strings, lists, dictionaries
etc.)
Syntax :
dir({object})
Parameters :
object [optional] : Takes object name
Returns :
dir() tries to return a valid list of attributes of the object it is called upon. Also,
dir() function behaves rather differently with different type of objects, as it aims
to produce the most relevant one, rather than the complete information.
• For Class Objects, it returns a list of names of all the valid attributes
and base attributes as well.
• For Modules/Library objects, it tries to return a list of names of all the
attributes, contained in that module.
• If no parameters are passed it returns a list of names in the current
local scope.
Code #1 : With and Without importing external libraries.
• Python3
# Python3 code to demonstrate dir()
# when no parameters are passed
# Note that we have not imported any modules
print(dir())
# Now let's import two modules
import random
import math
# return the module names added to
# the local namespace including all
# the existing ones as before
print(dir())
Output :
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__',
'__spec__']
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__',
'math', 'random']
Code #2 :
• Python3
# Python3 code to demonstrate dir() function
# when a module Object is passed as parameter.
# import the random module
import random
# Prints list which contains names of
# attributes in random function
print("The contents of the random library are::")
# module Object is passed as parameter
print(dir(random))
Output :
The contents of the random library are ::
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random',
'SG_MAGICCONST',
'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType',
'_Sequence',
'_Set', '__all__', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__',
'__name__', '__package__', '__spec__', '_acos', '_ceil', '_cos',
'_e', '_exp',
'_inst', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt',
'_test', '_test_generator',
'_urandom', '_warn', 'betavariate', 'choice', 'expovariate',
'gammavariate', 'gauss',
'getrandbits', 'getstate', 'lognormvariate', 'normalvariate',
'paretovariate', 'randint',
'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle',
'triangular', 'uniform',
'vonmisesvariate', 'weibullvariate']
Code #3 : Object is passed as parameters.
• Python3
# When a list object is passed as
# parameters for the dir() function
# A list, which contains
# a few random values
geeks = ["geeksforgeeks", "gfg", "Computer Science",
"Data Structures", "Algorithms" ]
# dir() will also list out common
# attributes of the dictionary
d = {} # empty dictionary
# dir() will return all the available
# list methods in current local scope
print(dir(geeks))
# Call dir() with the dictionary
# name "d" as parameter. Return all
# the available dict methods in the
# current local scope
print(dir(d))
Output :
['__add__', '__class__', '__contains__', '__delattr__',
'__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__',
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__',
'__init__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__',
'__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__reversed__',
'__rmul__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append',
'clear',
'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
['__class__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__gt__',
'__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
'__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__setitem__',
'__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy',
'fromkeys', 'get', 'items',
'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
Code #4 : User Defined – Class Object with an available __dir()__ method is
passed as parameter.
• Python3
# Python3 program to demonstrate working
# of dir(), when user defined objects are
# passed are parameters.
# Creation of a simple class with __dir()__
# method to demonstrate it's working
class Supermarket:
# Function __dir()___ which list all
# the base attributes to be used.
def __dir__(self):
return['customer_name', 'product',
'quantity', 'price', 'date']
# user-defined object of class supermarket
my_cart = Supermarket()
# listing out the dir() method
print(dir(my_cart))
Output :
['customer_name', 'date', 'price', 'product', 'quantity']
Applications :
• The dir() has it’s own set of uses. It is usually used for debugging
purposes in simple day to day programs, and even in large projects
taken up by a team of developers. The capability of dir() to list out all
the attributes of the parameter passed, is really useful when handling
a lot of classes and functions, separately.
• The dir() function can also list out all the available attributes for a
module/list/dictionary. So, it also gives us information on the
operations we can perform with the available list or module, which can
be very useful when having little to no information about the module. It
also helps to know new modules faster.