We write different codes and then execute them. This type of practice needs just a temporary program. But what you want to use a program for further use. It is possible with Python modules. In this article, we will discuss on what is modules in Python in details with examples.
Python modules are files that contain Python code. A module is a single file that may have multiple program definition inside for use.
To logically arrange our Python code into a single file we can use the Python modules. A module can contain a single statement, a simple or complex function. A module can also consist of Multiple methods and classes.
We can not only just arrange such code in a file, but also we can use them. Another important of modules is reusability.One of the best features of Python programming is reusability. Write code once and use them when needed.
How to create Python Modules
To create a module we have a create Python file. Creating a module is not a complicated process. We just have to write a code and save the code as Python file.
To create or save a Python file we have to use the .py extension. The .py extension indicates this a file that contains Python code.
#creating a Python module #save this file with .py extension def display(): print("I am from Module file") print("I will display a code")
Save the above code in your computer anywhere, with any name but with the .py extension.
How to use the Python Modules
Once we successfully create a Python module, the question arises how to use it? For this, we have to use the import statement.
An import statement will load all the functions, classes and codes from the module file. After importing the code, we can use them efficiently in our program.
import module module.display()
I am from Module file I will display a code
In above code, we have imported the last file name module.py. The file has one function display().
To use the method from the modules, we have to follow the below syntax.
Importing module from different dictionary
Whenever we use the import statement, it checks the search path for importing a module. A Search path is a list of directories which Python interpreter searches for the modules.
When we import all the built in modules, it is loaded directly. But when we include user define module the simple import statement is not enough.
The Python interpreter always searches the current directory of the file when we use the import statement. If the module exists in the directory, it will be loaded. If the file is not in the current directory, we will get an error.
To import a file from the different directory, we have to some another method.
First, we have to set the file path for the installation of the directory. To do so, we have to use the append() method.
import sys sys.path.append(path of directory)
In above syntax, first, we have to import the sys module. Once it’s done, we have to set the sys.path. To set we have to use the append() method.
In the append() method we have to pass the path to the directory where our module exists.
import sys sys.path.append('E:\Programs') import module module.display()
I am from Module file I will display a code
The from import Statement
The simple import statement will load all the methods, classes and expressions from the module. But if you want to include only one or two functions from the module, then we have to use the from import statement.
The general syntax for from import
from module_name import method_name1, method name2,...
To explain the from import statement we have to create the module which contains multiple functions. After creating the module, we will include one of the methods using the form import statement.
Code for calculator module.
def add(n1,n2): print(n1+n2) def minus(n1,n2): print(n1-n2) def multiply(n1,n2): print(n1*n2) def divide(n1,n2): print(n1/n2)
Code to import the add method in the program
from calculator import add print("Using the add method from the calculator module") add(1,3)
Using the add method from the calculator module 4
If you want to import all the methods from the modules using the from import statement, then you can use the from import * statement.
from module_name import *
The dir() method
If you do know all the names of the method available in the module and you want to. For that, you can use the dir() method.
The dir() method will list all the available methods, variable, and modules of the modules. In the dir() method we have to pass the name of the module for searching the list of functions.
import calculator print("Contents of calculator module") print(dir(calculator))
Contents of calculator module ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'divide', 'minus', 'multiply']
Scope of Variables in Python Modules
Earlier in articles of functions, we have covered the topic of the scope of variables. But the topic was only for the same program. Here we will talk about the extent of the variable between the modules.
A variable in a program is nothing but just a label given to the address of the memory. In Python, we have a dictionary that manages these variable.
The dictionary is known as a namespace. The namespace maintains the list of the variable created by the programmer. Not only the variable but their associated values.
In the dictionary of namespace the name of the variable act as a key and objects as values.
In modules, the scope of the variable remains same like the function. The local variable will remain same that we cannot access outside the method.
The global variable is available everywhere in the program but in the same module. We cannot access the global variable outside the modules. If we try to do so, the Python interpreter will give an error.
import calculator print("Accessing global variable outside the module") print(num)
Accessing global variable outside the module Traceback (most recent call last): File "E:\Programs\Python 3\check_module.py", line 4, in <module> print(num) NameError: name 'num' is not defined
Special functions for namespace
Like dir() that provide the list of all the modules. We have two unique methods that will return the name of the variable that we can access.
First is the globals(), when we call this method, it returns a dictionary. The dictionary contains a list of all the global variables that are accessible from the function.
import math print(globals().keys())
dict_keys(['__builtins__', 'math', '__doc__', '__file__', '__package__', '__name__', '__spec__', '__loader__'])
Second Method is locals() that also returns a dictionary. The dictionary will have all the name of the variables that can available locally in a method.
import math print(locals().keys())
dict_keys(['__spec__', '__loader__', 'math', '__package__', '__name__', '__builtins__', '__doc__', '__file__'])
Packages in Python
Python modules are collections of functions, variables, and statements. A package is a set of modules and sub packages.
A Package in Python is just a directory where other modules and sub directories are available. The package makes easier to import multiple modules.
Instead of importing multiple modules using multiple import statement, we just need to import package. Once we import a package we will import all the modules directly.
For example, I have a package name pack1. The pack1 package contains multiple modules so to import all the modules I will import the package.
Here we will conclude the topic of Python modules If any questions feel free to ask in comments below.