Python Import Module (Library/Package/File) System

The Python Import is statements are similar to the #include statements in C/C++ but different. It allows you to use functions defined elsewhere either in a standard module or package or your own modules. In this tutorial, you will learn about Python Import statements in detail with examples.

Python Import Module (Library ,Package, File) System

If you know some of the imported manners in another programming language, you will find in the code calls to functions of this kind < module_name >.< function >, Some of the import standard modules are in python is :

import getopt  
import os  
import re   
import string  
import sys  
import getpass  
import urllib  
import subprocess

Check it an example of File handling in python: Delete File, used a import the OS module to delete a file in python.

Why Python Import Module?

Because if you need any functionality in your app you need to write a code , for that you have to depend on other codes. That Time you need to import those module (like libraries) or package and use it.

Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

For example, the module sys allows you to do this:

import sys
#down if something
sys.exit(0)

It will terminate the program, you don’t have to write any code for the exit()function, it’s defined within the standard sys module.

Import module_name

Import is searches for the module initially in the local scope by calling __import__() function. The value returned by the function are then reflected in the output of the initial code.

Python Import module_name

This is an example of factorial in python, using a factorial function of standard math module.

import math
print(math.factorial(5))

Output : 120

Import from module_name.member_name

Python Import from module_name.member_name 3

fsum as a whole can be imported into our initial code, rather than importing the whole module.

from math import fsum
print(fsum([1, 2, 3, 1]))

Output : 7.0

from module_name import *

All the functions and constants can be imported using *.

from module_name import *

See this example not suing the math module, because all important to direct use.

from math import *

print(fsum([1, 2, 3, 1]))
print(factorial(5))

Output : 7.0

120

Bonus: What is Modules and How to create is must follow this tutorial: Python Modules Custom and Builtin.

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Python Import-Module Examples are in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.