Chapter 7
Chapter 7
Python Modules
Python Module is a file that contains built-in functions,
classes,its and variables. There are many Python modules, each
with its specific work.
In this article, we will cover all about Python modules, such as How
to create our own simple module, Import Python modules, From
statements in Python, we can use the alias to rename the module,
etc.
What is Python Module
A Python module is a file containing Python definitions and
statements. A module can define functions, classes, and variables. A
module can also include runnable code.
Grouping related code into a module makes the code easier to
understand and use. It also makes the code logically organized.
Create a Python Module
To create a Python module, write the desired code and save that in
a file with .py extension. Let’s understand it better with an example:
Example:
Let’s create a simple calc.py in which we define two functions,
one add and another subtract.
Python3
print(calc.add(10, 2))
Output:
12
Python Import From Module
Python’s from statement lets you import specific attributes from a
module without importing the module as a whole.
Import Specific Attributes from a Python module
Here, we are importing specific sqrt and factorial attributes from the
math module.
Python3
Output:
4.0
720
Import all Names
The * symbol used with the import statement is used to import all
the names from a module to a current namespace.
Syntax:
from module_name import *
What does import * do in Python?
The use of * has its advantages and disadvantages. If you know
exactly what you will be needing from the module, it is not
recommended to use *, else do so.
Python3
Output
4.0
720
Locating Python Modules
Whenever a module is imported in Python the interpreter looks for
several locations. First, it will check for the built-in module, if not
found then it looks for a list of directories defined in the sys.path.
Python interpreter searches for the module in the following manner
–
First, it searches for the module in the current directory.
If the module isn’t found in the current directory, Python
then searches each directory in the shell
variable PYTHONPATH. The PYTHONPATH is an environment
variable, consisting of a list of directories.
If that also fails python checks the installation-dependent
list of directories configured at the time Python is installed.
Directories List for Modules
Here, sys.path is a built-in variable within the sys module. It contains
a list of directories that the interpreter will search for the required
module.
Python3
# importing sys.path
print(sys.path)
Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’,
‘/usr/lib/python3.8’, ‘/usr/lib/python3.8/lib-dynload’, ”,
‘/home/nikhil/.local/lib/python3.8/site-packages’,
‘/usr/local/lib/python3.8/dist-packages’, ‘/usr/lib/python3/dist-
packages’,
‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’,
‘/home/nikhil/.ipython’]
Python3
Output
4.0
720
# Sine of 2 radians
print(math.sin(2))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87 Python Packages
We usually organize our files in different folders and subfolders
based on some criteria, so that they can be managed easily and
efficiently. For example, we keep all our games in a Games folder
and we can even subcategorize according to the genre of the game
or something like that. The same analogy is followed by the
packages in Python.
Table of Content
What is a Python Package?
How to Create Package in Python?
Python Packages for Web frameworks
Python Packages for AI & Machine Learning
Python Packages for GUI Applications
Python Packages for Web scraping & Automation
Python Packages for Game Development
What is a Python Package?
Python Packages are a way to organize and structure your Python
code into reusable components. Think of it like a folder that contains
related Python files (modules) that work together to provide certain
functionality. Packages help keep your code organized, make it
easier to manage and maintain, and allow you to share your code
with others. They’re like a toolbox where you can store and organize
your tools (functions and classes) for easy access and reuse in
different projects.
How to Create Package in Python?
Creating packages in Python allows you to organize your code into
reusable and manageable modules. Here’s a brief overview of how
to create packages:
Create a Directory: Start by creating a directory (folder)
for your package. This directory will serve as the root of
your package structure.
Add Modules: Within the package directory, you can add
Python files (modules) containing your code. Each module
should represent a distinct functionality or component of
your package.
Init File: Include an __init__.py file in the package directory.
This file can be empty or can contain an initialization code
for your package. It signals to Python that the directory
should be treated as a package.
Subpackages: You can create sub-packages within your
package by adding additional directories containing
modules, along with their own __init__.py files.
Importing: To use modules from your package, import
them into your Python scripts using dot notation. For
example, if you have a module named module.py inside a
package named mypackage, you would import it like this:
from mypackage import module.
Distribution: If you want to distribute your package for
others to use, you can create a setup.py file using Python’s
setuptools library. This file defines metadata about your
package and specifies how it should be installed.
Code Example
Here’s a basic code sample demonstrating how to create a simple
Python package:
1. Create a directory named mypackage.
2. Inside mypackage, create two Python files: module1.py and
module2.py.
3. Create an __init__.py file inside mypackage (it can be
empty).
4. Add some code to the modules.
5. Finally, demonstrate how to import and use the modules
from the package.
mypackage/
│
├── __init__.py
├── module1.py
└── module2.py
Example: Now, let’s create a Python script outside the mypackage
directory to import and use these modules:
Python
Python
Python
# module1.py
def greet(name):
print(f"Hello, {name}!")
When you run the script, you should see the following output:
Hello, Alice!
The result of addition is: 8
Python Packages for Web frameworks
In this segment, we’ll explore a diverse array of Python frameworks
designed to streamline web development. From lightweight and
flexible options like Flask and Bottle to comprehensive frameworks
like Django and Pyramid, we’ll cover the spectrum of tools available
to Python developers. Whether you’re building simple web
applications or complex, high-performance APIs, there’s a
framework tailored to your needs.
Flask: Flask is a lightweight and flexible web framework for
Python. It’s designed to make getting started with web
development in Python quick and easy, with a simple and
intuitive interface. Flask provides tools and libraries to help
you build web applications, APIs, and other web services.
Django: Django is a Python web framework for building web
applications quickly and efficiently. It follows the DRY
principle and includes features like URL routing, database
management, and authentication, making development
easier. It’s highly customizable and widely used in web
development.
FastAPI: Python FastAPI is a high-performance web
framework for building APIs quickly and efficiently. It’s easy
to use, based on standard Python-type hints, and offers
automatic interactive documentation. FastAPI is designed to
be fast, easy to learn, and ideal for building modern web
APIs.
Pyramid: Python Pyramid is a lightweight web framework for
building web applications in Python. It emphasizes flexibility,
allowing developers to choose the components they need
while providing powerful features for handling HTTP
requests, routing, and templating.
Tornado: Python Tornado is a web framework and
asynchronous networking library designed for handling high
concurrency with non-blocking I/O operations. It’s ideal for
building real-time web applications and APIs due to its
efficient event-driven architecture.
Falcon: Python Falcon is a lightweight web framework
designed for building high-performance APIs quickly and
easily. It focuses on simplicity, speed, and minimalism,
making it ideal for creating RESTful APIs with minimal
overhead.
CherryPy: CherryPy is a minimalist Python web framework
for building web applications. It provides a simple and
intuitive interface for handling HTTP requests, allowing
developers to focus on their application logic without
dealing with the complexities of web server management.
Bottle: Python Bottle is a lightweight web framework for
building small web applications in Python with minimal
effort and overhead. It’s designed to be simple and easy to
use, making it great for prototyping and creating simple
APIs or web services.
Web2py: Web2py is a free open-source web framework for
agile development of secure database-driven web
applications. It’s written in Python and offers features like an
integrated development environment (IDE), simplified
deployment, and support for multiple database backends.
Python Packages for AI & Machine Learning
In this segment, we’ll explore a selection of essential Python
packages tailored for AI and machine learning applications. From
performing statistical analysis and visualizing data to delving into
advanced topics like deep learning, natural language processing
(NLP), generative AI, and computer vision, these packages offer a
comprehensive toolkit for tackling diverse challenges in the field.
Statistical Analysis
Here, we’ll explore key Python libraries for statistical analysis,
including NumPy, Pandas, SciPy, XGBoost, StatsModels, Yellowbrick,
Arch, and Dask-ML. From data manipulation to machine learning and
visualization, these tools offer powerful capabilities for analyzing
data effectively.
NumPy
Pandas
SciPy
XGBoost
StatsModels
Yellowbrick
Arch
Dask-ML
Data Visualization
Here, we’ll explore a variety of Python libraries for creating stunning
visualizations. From Matplotlib to Seaborn, Plotly to Bokeh, and Altair
to Pygal, we’ve got you covered. By the end, you’ll be equipped to
transform your data into compelling visual narratives.
Matplotlib
Seaborn
Plotly
Bokeh
Altair
Pygal
Plotnine
Dash
Deep Learning
Here, we’ll explore essential frameworks like TensorFlow, PyTorch,
Keras, and more. From Scikit-learn for supervised learning to Fastai
for advanced applications, we’ll cover a range of tools to unlock the
potential of deep learning.
Scikit-learn
TensorFlow
torch
Keras
Keras-RL
Lasagne
Fastai
Natural Processing Language
Here, we’ll explore essential NLP tools and libraries in Python,
including NLTK, spaCy, FastText, Transformers, AllenNLP, and
TextBlob.
NLTK
spaCy
FastText
Transformers
fastText
AllenNLP
TextBlob
Genrative AI
In this segment, we’ll explore a range of powerful tools and libraries
that enable the creation of artificial intelligence models capable of
generating novel content. From the renowned deep learning
framework Keras to the natural language processing library spaCy,
we’ll cover the essential tools for building generative AI systems.
Keras
spaCy
generative
GPy
Pillow
ImageIO
Fastai
Computer Vision
Here, we’ll explore essential Python libraries like OpenCV,
TensorFlow, and Torch, alongside specialized tools such as scikit-
image and Dlib. From basic image processing to advanced object
detection, these libraries empower you to tackle diverse computer
vision tasks with ease.
OpenCV
TensorFlow
torch
scikit-image
SimpleCV
ImageAI
imageio
Dlib
Theano
Mahotas
Python Packages for GUI Applications
Graphical User Interface (GUI) development is a vital aspect of
modern software applications, enabling intuitive user interactions
and enhancing user experience. In this section, we’ll explore a
variety of Python packages tailored for GUI application development,
including Tkinter, PyQt5, Kivy, PySide, PySimpleGUI, PyGTK, and
more.
Tkinter: Python Tkinter is a standard GUI (Graphical User
Interface) toolkit for Python. It allows developers to create
desktop applications with graphical interfaces using widgets
such as buttons, labels, and entry fields. Tkinter is easy to
use and comes pre-installed with most Python distributions,
making it a popular choice for creating simple desktop
applications. Some more Pakages for Tkinter are:
tk-tools
tkcalendar
tkvideoplayer
tkfilebrowser
PyQT5: PyQt5 is a Python library that enables developers to
create desktop applications with graphical user interfaces
(GUIs). It’s based on the Qt framework, offering a wide
range of tools and widgets for building powerful and
customizable applications efficiently.
Kivy: Python Kivy is an open-source Python library used for
developing multi-touch applications. It allows developers to
create cross-platform applications that run on Android, iOS,
Windows, Linux, and macOS with a single codebase. Kivy
provides a comprehensive set of tools for building user
interfaces and handling touch events, making it suitable for
developing interactive and responsive applications.
PySide: Python PySide is a set of Python bindings for the Qt
application framework. It allows developers to create
graphical user interfaces (GUIs) using Qt tools and libraries
within Python code, enabling cross-platform desktop
application development with ease.
PySimpleGUI: PySimpleGUI is a Python library for creating
simple and easy-to-use graphical user interfaces (GUIs) for
desktop applications. It aims to simplify GUI development by
providing a straightforward interface and works across
multiple platforms.
PyGTK: PyGTK is a set of Python bindings for the GTK (GIMP
Toolkit) library, which is a popular toolkit for creating
graphical user interfaces (GUIs). With PyGTK, developers
can create cross-platform GUI applications in Python using
GTK’s rich set of widgets and tools.
Python Packages for Web scraping &
Automation
In this concise guide, we’ll explore a curated selection of powerful
Python packages tailored for web scraping and automation tasks.
From parsing HTML with Beautiful Soup to automating browser
interactions with Selenium, we’ll cover the essentials you need to
embark on your web scraping and automation journey. Additionally,
we’ll introduce other handy tools like MechanicalSoup, urllib3,
Scrapy, Requests-HTML, Lxml, pyautogui, schedule, and Watchdog,
each offering unique functionalities to streamline your development
process.
Request: Python Requests is a versatile HTTP library for
sending HTTP requests in Python. It simplifies interaction
with web services by providing easy-to-use methods for
making GET, POST, PUT, DELETE, and other HTTP requests,
handling headers, parameters, cookies, and more.
BeautifulSoup: Python BeautifulSoup is a library used for
parsing HTML and XML documents. It allows you to extract
useful information from web pages by navigating the HTML
structure easily.
Selenium: Python Selenium is a powerful tool for
automating web browsers. It allows you to control web
browsers like Chrome or Firefox programmatically, enabling
tasks such as web scraping, testing, and automating
repetitive tasks on websites.
MechanicalSoup: Python MechanicalSoup is a Python
library for automating interaction with websites. It simplifies
tasks like form submission, navigation, and scraping by
combining the capabilities of the Requests and
BeautifulSoup libraries.
urllib3: Python urllib3 is a powerful HTTP client library for
Python, allowing you to make HTTP requests
programmatically with ease. It provides features like
connection pooling, SSL verification, and support for various
HTTP methods.
Scrapy: Python Scrapy is a powerful web crawling and web
scraping framework used to extract data from websites. It
provides tools for navigating websites and extracting
structured data in a flexible and efficient manner.
Requests-HTML: Python Requests-HTML is a Python library
that combines the power of the Requests library for making
HTTP requests with the flexibility of parsing HTML using CSS
selectors. It simplifies web scraping and makes it easy to
extract data from HTML documents.
Lxml: Python lxml is a powerful library used for processing
XML and HTML documents. It provides efficient parsing,
manipulation, and querying capabilities, making it a popular
choice for working with structured data in Python.
pyautogui: PyAutoGUI is a Python library for automating
tasks by controlling the mouse and keyboard. It enables
users to write scripts to simulate mouse clicks, keyboard
presses, and other GUI interactions.
schedule: Python Schedule is a library that allows you to
schedule tasks to be executed at specified intervals or
times. It provides a simple interface to create and manage
scheduled jobs within Python programs.
Watchdog: Python Watchdog is a library that allows you to
monitor filesystem events in Python, such as file creations,
deletions, or modifications. It’s useful for automating tasks
based on changes in files or directories, like updating a
database when new files are added to a folder.
Python Packages for Game Development
Here, we’ll explore the exciting world of game development in
Python, leveraging powerful packages and libraries to bring your
gaming ideas to life. Let’s dive in and discover the tools that will
empower you to create immersive and entertaining gaming
experiences.
PyGame: PyGame is a set of libraries and tools for creating
video games and multimedia applications using Python. It
provides functions for handling graphics, sound, input
devices, and more, making it easier to develop games with
Python.
Panda3D: Python Panda3D is a game development
framework that provides tools and libraries for creating 3D
games and simulations using the Python programming
language. It offers features for rendering graphics, handling
input, and managing assets, making it suitable for both
hobbyists and professional game developers.
Pyglet: Pyglet is a Python library used for creating games
and multimedia applications. It provides tools for handling
graphics, sound, input devices, and windowing. With Pyglet,
developers can build interactive experiences efficiently in
Python.
Arcade: Python Arcade is a beginner-friendly Python library
for creating 2D games. It provides tools for handling
graphics, sound, input devices, and other game-related
functionalities, making game development accessible and
fun.
PyOpenGL: PyOpenGL is a Python binding to OpenGL, a
powerful graphics library for rendering 2D and 3D graphics.
It allows Python developers to access OpenGL’s functionality
for creating interactive visual applications, games,
simulations, and more.
Cocos2d: Python Cocos2d is a simple and powerful game
development framework for Python. It provides tools and
libraries for creating 2D games, making game development
more accessible and efficient for Python developers.