Python Modules

07 Jun, 2022
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.
Python3
# A simple module, calc.py  def add(x, y):    return (x+y)  def subtract(x, y):    return (x-y)
We can import the functions, classes defined in a module to another module using the import statement in some other Python source file. 
Syntax:
import module
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.
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.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Python3
# importing  module calc.pyimport calc  print(calc.add(10, 2))
Output:
12
Python’s from statement lets you import specific attributes from a module without importing the module as a whole.
Python3
# importing sqrt() and factorial from the# module mathfrom 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
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 *
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.
Python3
# importing sqrt() and factorial from the# module mathfrom math import *  # if we simply do "import math", then# math.sqrt(16) and math.factorial()# are required.print(sqrt(16))print(factorial(6))
4.0
720
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.
Python3
# importing sys moduleimport sys  # importing sys.pathprint(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’]
We can rename the module while importing it using the as keyword. 
Python3
# importing sqrt() and factorial from the# module mathimport math as gfg  # if we simply do "import math", then# math.sqrt(16) and math.factorial()# are required.print(gfg.sqrt(16))print(gfg.factorial(6))
4.0
720
The dir() built-in function returns a sorted list of strings containing the names defined by a module. The list contains the names of all the modules, variables, and functions that are defined in a module.
Python3
#  Import built-in module  randomimport  randomprint(dir(random))
  
Output:
 
[‘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’, ‘_bisect’, ‘_ceil’, ‘_cos’, ‘_e’, ‘_exp’, ‘_inst’, ‘_itertools’, ‘_log’, ‘_pi’, ‘_random’, ‘_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’]
Code Snippet illustrating python built-in modules: 
 
Python3
# importing built-in module mathimport math  # using square root(sqrt) function contained # in math moduleprint(math.sqrt(25))   # using pi function contained in math moduleprint(math.pi)   # 2 radians = 114.59 degreesprint(math.degrees(2))    # 60 degrees = 1.04 radiansprint(math.radians(60))    # Sine of 2 radiansprint(math.sin(2))    # Cosine of 0.5 radiansprint(math.cos(0.5))    # Tangent of 0.23 radiansprint(math.tan(0.23))   # 1 * 2 * 3 * 4 = 24print(math.factorial(4))    # importing built in module randomimport random  # printing random integer between 0 and 5print(random.randint(0, 5))    # print random floating point number between 0 and 1print(random.random())    # random number between 0 and 100print(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 listprint(random.choice(List))     # importing built in module datetimeimport datetimefrom datetime import dateimport time  # Returns the number of seconds since the# Unix Epoch, January 1st 1970print(time.time())    # Converts a number of seconds to a date objectprint(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

    
        My Personal Notes
        arrow_drop_up
    
    
        
        
            
            Save
        
    
                        
fridayda13
RajuKumar19
nikhilaggarwal3
sagartomar9927
amartyaniel20

Python

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()