Module import and from in python

In this class, we discuss Module import and from in python.

For Complete YouTube Video: Click Here

Module in Python

The reader should have a prior understanding of functions and class. Click here.

A module in python is a python file.

A python file has a .py extension.

The python file name. we call it module name.

In our course, we are using a jupyter notebook.

The python file in the jupyter notebook will have a .ipynb extension.

Take an example and understand how to convert to a .py file.

The example is given below.

def function():
    print("this is function in module testmodule")


x={"name":"suresh","age":30}



class test:
    def f(self):
        print("This is f method in testmodule class test")

The above python file in the jupyter notebook contains one function, one dictionary, and one class.

To convert this .ipynb file to .py file.

Go to file and download as .py file. The name of the file is given as Testmodule.

Now we have a python file with the Testmodule.py extension.

After downloading this python file, copy this file and paste it into the folder where other programs need the code written in this file.

We can import the file Testmodule using the import function in python.

After importing, we can use the functions and classes in the file Testmodule.

An example is given below.

#importing a module
import testmodule as tm 

tm.function() #calling a function from module
tm.x # calling a variable from module
ob1=tm.test()
ob1.f()

import and as in python

import Testmodule as tm

import keyword is used to import the file. And as is used to alias the file name.

We did a shortcut to the file name Testmodule as tm.

tm.function() will call the function present in Testmodule.

In the same way, we can access the variables and define an object to the class in the Testmodule. as shown in the above example.

dir function in python

dir function is used to display the list of variables, functions, and classes in the module.

An example is shown below.

# dir function
y=dir(tm)
print(y)

Output:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'function', 'test', 'x']

The output of the above code shows the function, variables, and class.

The other names are default functions to any module.

from keyword in python

Importing the complete module is not needed.

We can import a particular class or function from the module using from keyword.

An example is shown below.

# use from to import the functions and variables required
from testmodule import function
function()

In the above program, from Testmodule import function will only import the function named function in Testmodule.