In this Python guide, we are going to learn about Python modules. Modules in Python are most important because the module makes it easy to work with the python program. if you want to learn Python programming, Then you can’t ignore Python modules.
In this guide, we will see all about the Python modules along with examples. At the end of this article, you will completely familiar with the Python module.
Headings of Contents
Python Modules
Python modules refer to the python file containing statements and definitions. Python files can contain classes or functions and so on with .py extension.
If you write any Python program, Then that file is called the Python module. Suppose we have python file named testing.py which contain statement and definitions.
Note:- Python module’s has must be .py extension.
Create a Python modules
To create the modules in Python, you have to write your Python program in a file and save it with a .py extension.
Suppose we have a file named testing.py that contains some Python program.
Example
testing.py file contains following code.
#class with parameters
class Student:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def details(self):
print(f"My name is {self.first_name + ' ' + self.last_name} and i am {self.age} years old.")
#class without parameters
class Message:
def printMessage(self):
print("Welcome to programming Funda.")
#function to calculate addition of two numbers.
def addition(a, b):
print(f"Addition of {a} and {b}:- {a+b}.")
Use Python Modules
To use the above-created module in another python program, you have to import testing.py using the import keyword.
We have another python file in the current working directory, we will use the module and its class and function.
Example
import testing
#Create object of Student class
st1 = testing.Student('John','Doe', 23)
#call the function to print details
st1.details()
#create the object of class Message
m1 = testing.Message()
m1.printMessage()
#call the function to calculate the addition of two number
testing.addition(12, 24)
Output
My name is Vishvajit Rao and i am 23 years old.
Welcome to programming Funda.
Addition of 12 and 24:- 36.
Important specific part
Sometimes we need to import only specific functions, variables, and classes from the module then we need to use from keyword.
Example:
from testing import Student, Message, addition
#Create object of Student class
st1 = Student('Vishvajit','Rao', 23)
#call the function to print details
st1.details()
#create the object of class Message
m1 = Message()
m1.printMessage()
#call the function to calculate the addition of two number
addition(12, 24)
Output
My name is Vishvajit Rao and i am 23 years old.
Welcome to programming Funda.
Addition of 12 and 24:- 36.
Import all the statements
To import all the function, class from module, use asterisk ( * ) symbol.
Example:
from testing import *
#Create object of Student class
st1 = Student('Ammy','Jackson', 20)
#call the function to print details
st1.details()
#create the object of class Message
m1 = Message()
m1.printMessage()
#call the function to calculate the addition of two number
addition(12, 24)
Output
My name is Ammy Jackson and i am 20 years old.
Welcome to programming Funda.
Addition of 12 and 24:- 36.
Re-naming a module
You can create a alias name when you import a module, by using as keyword.
Example:
import testing as ts
#Create object of Student class
st1 = ts.Student('Programming','Funda', 3)
#call the function to print details
st1.details()
#create the object of class Message
m1 = ts.Message()
m1.printMessage()
#call the function to calculate the addition of two number
ts.addition(12, 24)
Output
My name is Programming Funda and i am 3 years old.
Welcome to programming Funda.
Addition of 12 and 24:- 36.
Built-in module
Python provides lots of built-in functions that are very useful in Python programming, you can import whenever you like.
Example:
Import and use datetime module.
import datetime
data = datetime.datetime.now()
print(data)
Using dir() function
In Python there are various built-in modules, If you list all the function and variable names from the Python modules, then you can use the dir() function.
Example:
List all the defined names belonging to the os module.
import os
x = dir(os)
print(x)
Output
['DirEntry', 'F_OK', 'GenericAlias', 'Mapping', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_AddedDllDirectory', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_check_methods', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_walk', '_wrap_close', 'abc', 'abort', 'access', 'add_dll_directory', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'unsetenv', 'urandom', 'utime', 'waitpid', 'waitstatus_to_exitcode', 'walk', 'write']
Conclusion
In this article, you have learned all about the Python modules along with examples.
module in Python is the most important thing, you can’t ignore modules in Python ever. Python modules make very to work with python programming.
If you like this article, please share it and keep visiting for further interesting Python tutorials.
For reference:- Click Here