python


Python Modules


Modules

Modules can be defined as a file which contains Python statements and definitions.
The filename in the module should contain suffix .py.
Basically Modules are used to breakdown the large files into various small organized files. We can create our fuction in a particular file and import that function into the other file. It will help you by reusing of codes.There is no need to type codes for same function again and again.

Example:


def div(a,b):

    #here div function defines the divide operation
    result=a/b
    print(float(result))

We save the above program file as division.py


Import Modules in Python

We can import the module in another module i.e in another file here.In python import keyword is used to do this.
To import our module division.Type the following code in the python interpreter.


>>> import division

And for accessing the function of the module dot(.) operator is used as you can see in the below example.

Syntax:


modulename.function()
Example:


>>>division.div(35,7)
5.0
Renaming of module

We can create a alias for module by using as keyword


import math as mt

In the above example we imported a module math as mt. Now mt can be written in the place of math.

There are various ways for accessing a function from a module with the help of import statement.

  1. Python import statement
  2. We can simply use import keyword in this type.

    
    import math as mt
    print("the value of e:",mt.e)
    
    
  3. Python from...import statement
  4. Here, we import the speciic names according to necessity from amodule without importing the whole module.

    
    from math import e
    print("the value of e is:",e)
    
    

    Note: For importing multiple names comma(,) is used as a seperable.

  5. Import all names
  6. In this type,* is used to import all the names.

    
    from math import *
    print("the value of e is:",e)
    
    
    Output for all above code:
    
    The value of e is:2.718281828459045
    
Using dir() function

The dir() is used to list out the all functions in a module.It is a built-in function.This will also list the functions created by you.
We can use dir() in our module division


>>>dir(division)

There are various types of built-in modules available in python like math as we seen above.There are also some more examples like numpy,matplotlib etc.
For checking out the modules,Open your python shell and write the following code:


>>>help('modules')

The above code will display all the built-in modules come with python.