Skip to content
- Tutorials
- Python Tutorial
- Taking Input in Python
- Python Operators
- Python Data Types
- Python Loops and Control Flow
- Python Functions
- Python OOPS Concept
- Python Data Structures
- Python Exception Handling
- Python File Handling
- Python Exercises
- Java
- Java Programming Language
- Java Collections
- Java 8 Tutorial
- Java Programs
- Java Interview Questions
- Java Exercises
- Java Quiz
- Java Projects
- Advance Java
- Programming Languages
- System Design
- Interview Corner
- Computer Science Subjects
- DevOps
- Linux
- Software Testing
- Databases
- Android
- Excel
- Mathematics
- Python Tutorial
- DSA
- Data Structures
- Algorithms
- Analysis of Algorithms
- Searching Algorithms
- Sorting Algorithms
- Greedy Algorithms
- Dynamic Programming
- Graph Algorithms
- Pattern Searching
- Recursion
- Backtracking
- Divide and Conquer
- Mathematical Algorithms
- Geometric Algorithms
- Bitwise Algorithms
- Randomized Algorithms
- Branch and Bound
- Algorithms Tutorial
- DSA Tutorial
- Practice
- All DSA Problems
- Problem of the Day
- Company Wise Coding Practice
- GfG SDE Sheet
- Practice Problems Difficulty Wise
- Language Wise Coding Practice
- Curated DSA Lists
- Competitive Programming
- Company Wise SDE Sheets
- DSA Cheat Sheets
- Top Interview Questions
- Puzzles
- Data Science
- Web Tech
- Courses
-
Last Updated : 15 Feb, 2018
Summarize
Comments
Improve
Packages are a way of structuring many packages and modules which helps in a well-organized hierarchy of data set, making the directories and modules easy to access. Just like there are different drives and folders in an OS to help us store files, similarly packages help us in storing other sub-packages and modules, so that it can be used by the user when necessary.Creating and Exploring Packages
To tell Python that a particular directory is a package, we create a file named __init__.py inside it and then it is considered as a package and we may create other modules and sub-packages within it. This __init__.py file can be left blank or can be coded with the initialization code for the package.
To create a package in Python, we need to follow these three simple steps:- First, we create a directory and give it a package name, preferably related to its operation.
- Then we put the classes and the required functions in it.
- Finally we create an __init__.py file inside the directory, to let Python know that the directory is a package.
Example of Creating Package
Let’s look at this example and see how a package is created. Let’s create a package named Cars and build three modules in it namely, Bmw, Audi and Nissan.
- First we create a directory and name it Cars.
- Then we need to create modules. To do this we need to create a file with the name Bmw.py and create its content by putting this code into it.
# Python code to illustrate the Modules
class
Bmw:
# First we create a constructor for this class
# and add members to it, here models
def
__init__(
self
):
self
.models
=
[
'i8'
,
'x1'
,
'x5'
,
'x6'
]
# A normal print function
def
outModels(
self
):
print
(
'These are the available models for BMW'
)
for
model
in
self
.models:
print
(
'\t%s '
%
model)
Then we create another file with the name Audi.py and add the similar type of code to it with different members.
# Python code to illustrate the Module
class
Audi:
# First we create a constructor for this class
# and add members to it, here models
def
__init__(
self
):
self
.models
=
[
'q7'
,
'a6'
,
'a8'
,
'a3'
]
# A normal print function
def
outModels(
self
):
print
(
'These are the available models for Audi'
)
for
model
in
self
.models:
print
(
'\t%s '
%
model)
Then we create another file with the name Nissan.py and add the similar type of code to it with different members.
# Python code to illustrate the Module
class
Nissan:
# First we create a constructor for this class
# and add members to it, here models
def
__init__(
self
):
self
.models
=
[
'altima'
,
'370z'
,
'cube'
,
'rogue'
]
# A normal print function
def
outModels(
self
):
print
(
'These are the available models for Nissan'
)
for
model
in
self
.models:
print
(
'\t%s '
%
model)
- Finally we create the __init__.py file. This file will be placed inside Cars directory and can be left blank or we can put this initialisation code into it.
from
Bmw
import
Bmw
from
Audi
import
Audi
from
Nissan
import
Nissan
- import in Packages
Suppose the cars and the brand directories are packages. For them to be a package they all must contain __init__.py file in them, either blank or with some initialization code. Let’s assume that all the models of the cars to be modules. Use of packages helps importing any modules, individually or whole.
Suppose we want to get Bmw i8. The syntax for that would be:'import' Cars.Bmw.x5
While importing a package or sub packages or modules, Python searches the whole tree of directories looking for the particular package and proceeds systematically as programmed by the dot operator.
If any module contains a function and we want to import that. For e.g., a8 has a function get_buy(1) and we want to import that, the syntax would be:import Cars.Audi.a8Cars.Audi.a8.get_buy(1)
While using just the import syntax, one must keep in mind that the last attribute must be a subpackage or a module, it should not be any function or class name.
- ‘from…import’ in Packages
Now, whenever we require using such function we would need to write the whole long line after importing the parent package. To get through this in a simpler way we use ‘from’ keyword. For this we first need to bring in the module using ‘from’ and ‘import’:from Cars.Audi import a8
Now we can call the function anywhere using
a8.get_buy(1)
There’s also another way which is less lengthy. We can directly import the function and use it wherever necessary. First import it using:
from Cars.Audi.a8 import get_buy
Now call the function from anywhere:
get_buy(1)
- ‘from…import *’ in Packages
While using the from…import syntax, we can import anything from submodules to class or function or variable, defined in the same module. If the mentioned attribute in the import part is not defined in the package then the compiler throws an ImportError exception.
Importing sub-modules might cause unwanted side-effects that happens while importing sub-modules explicitly. Thus we can import various modules at a single time using * syntax. The syntax is:from Cars.Chevrolet import *
This will import everything i.e., modules, sub-modules, function, classes, from the sub-package.
Now, let’s use the package that we created. To do this make a sample.py file in the same directory where Cars package is located and add the following code to it:
# Import classes from your brand new package
from
Cars
import
Bmw
from
Cars
import
Audi
from
Cars
import
Nissan
# Create an object of Bmw class & call its method
ModBMW
=
Bmw()
ModBMW.outModels()
# Create an object of Audi class & call its method
ModAudi
=
Audi()
ModAudi.outModels()
# Create an object of Nissan class & call its method
ModNissan
=
Nissan()
ModNissan.outModels()
Various ways of Accessing the Packages
Let’s look at this example and try to relate packages with it and how can we access it.
Please Login to comment...
Similar Reads
What is the difference between Python's Module, Package and Library?
In this article, we will see the difference between Python's Module, Package, and Library. We will also see some examples of each to things more clear. What is Module in Python? The module is a simple Python file that contains collections of functions and global variables and with having a .py extension file. It is an executable file and to organiz
2 min read
How to Install SimpleJson Package for Python in MacOS?
SimpleJson is an open-source Python package. It is a fast, simple, and extensible Python JSON encoder and decoder. The encoder can be customized to provide serialization in any case without special support for serializing objects. For this purpose, the dump should be used as the default parameter. The decoder can handle any encoded JSON string (def
2 min read
Install Python package using Jupyter Notebook
Jupyter Notebook is an open-source web application that is used to create and share documents that contain data in different formats which includes live code, equations, visualizations, and text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. Jupyter ha
3 min read
How to install MySQL connector package in Python?
Prerequisite: Python Language Introduction MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. A connector is employed when we have to use MySQL with other programmin
2 min read
Humanize Package in Python
Humanize is a package in python which contains various humanization utilities like turning a number into a human-readable size or throughput or number. In this article, we will discuss how to install this package and what are the different utilities present in this package. Installation: To install this package, we will use pip a command. Python pi
3 min read
Python - Database Manager (dbm) package
In this article, we will learn about dbm, a package in the built-in library of Python. The dbm package in Python provides a simple dictionary-like interface of the form DBM (DataBase Manager) generally used in the Unix operating system. dbm stores data in simple key-value pair form like a dictionary, making it easier to insert, edit and retrieve da
4 min read
Snakebite Python Package For Hadoop HDFS
Prerequisite: Hadoop and HDFS Snakebite is a very popular python package that allows users to access HDFS using some kind of program with python application. The Snakebite Python Package is developed by Spotify. Snakebite also provides a Python client library. The protobuf messages are used by the snakebite client library to directly communicate wi
3 min read
Spikes package in Python
spikes is a package in Python, a command-line utility used for displaying bar graphs on the terminal, therefore can be used for quick analysis Installation: Run the following pip command on the terminal: pip install spikes It's recommend to run all program on terminal of IDE as PowerShell doesn't support few output characters Syntax: spike [space s
1 min read
How to Build a Python package?
In this article, we will learn how to develop the package in Python. Packages are nothing but a collection of programs designed to perform a certain set of task(s). Packages are of two types, namely Built-in Packages like collection, datetime, sqlite, etc.External packages like flask, django, tensorflow, etc.Creating a package First, we need to thi
5 min read
How to install pyscopg2 package in Python?
psycopg2 is the most popular PostgreSQL database adapter for the Python programming language. It is a DB API 2.0 compliant PostgreSQL driver is actively developed. It is designed for heavily multi-threaded applications that create and destroy lots of cursors and create a large number of "INSERTs" or "UPDATEs". Installation: To install this module f
1 min read
How to Install SimpleJson Package for Python?
In this article, we will see how to Install SimpleJson Package for Python SimpleJson is an open-source package in python. It is a fast, simple, correct, and extensible JSON encoder and decoder for python. Python's built-in JSON library has been externally developed to provide backward compatibility with Python 3.3+ and older. Here, Encoders can be
2 min read
How to Install python 'bottle package' on Linux?
py-bottle is a lightweight micro-framework for developing small web apps and it supports request dispatching (Routes) with URL parameter support, templates, a built-in HTTP Server, and adapters for several third-party WSGI/HTTP-server and template engines are all included in a single file with no dependencies except the Python standard library. In
2 min read
How to Install "Python-PyPDF2" package on Linux?
PyPDF2 is a Python module for extracting document-specific information, merging PDF files, separating PDF pages, adding watermarks to files, encrypting and decrypting PDF files, and so on. PyPDF2 is a pure python module so it can run on any platform without any platform-related dependencies on any external libraries or packages. So, in this article
2 min read
How to Install Python-web2py package on Linux?
Web2py is a Python package that helps web developers to create dynamic online content. Although a web developer may construct a form from scratch if necessary, Web2py is meant to assist decrease tiresome web development activities like building web forms from scratch. So, in this article, we'll use the PIP manager to install the Web2py Python packa
2 min read
How to Install PyBullet package in Python on Linux?
PyBullet is a Python library based on the Bullet Physics SDK for physics simulation and robotics. It works with a variety of sensors, actuators, and terrains. Basically, this is a fantastic library for anyone who is just getting started with robotics or physics modeling. So, in this tutorial, we'll use the PIP manager to install the PyBullet packag
2 min read
How to Install Python-pyautogui package on Linux?
PyAutoGUI allows your Python programs to automate interactions with other apps by controlling the mouse and keyboard. The API was created with simplicity in mind. PyAutoGUI is a cross-platformed library that works on Windows, macOS, and Linux and runs on Python 2 and 3. We will install the PyAutoGUI package in Python on the Linux operating system i
2 min read
How to Install Python-pyzmail package on Linux?
Pyzmail is a high-level Python mail library. It has methods and classes that make reading, writing, and sending emails easier. There's no reason why managing emails with Python should be more complex than with popular mail clients like Outlook or Thunderbird. The intricacy of the MIME structure and MIME encoding/decoding is hidden by the pyzmail pa
2 min read
How to Install maskpass package in Python on Linux?
Maskpass is a Python package that may be used to conceal user passwords while they are being entered. When programs interface with users via terminal, the Maskpass modules provide a safe solution to handle password prompts. Maskpass is a cross-platform library that works on Windows, Linux, and Mac OS X. In this article, we'll show you how to instal
2 min read
PGCLI: Python package for a interactive Postgres CLI
PGCLI is a Python package that is used as an interactive command-line interface for the PostgreSQL database server. For following with the article, make sure you have PostgreSQL installed and set up in your local system. You can follow the guide for Windows, Linux and macOS from the guide. Also for performing any operations or testing out the packa
3 min read
How to install a Python Package from a GitHub Repository
In this article we will learn how to install a pip package from a git repository, PIP supports installing from various version control systems (VCS). This support requires a working executable to be available (for the version control system being used). It is used through URL prefixes: Git -- git+ Mercurial -- hg+ Subversion -- svn+ Bazaar -- bzr+I
2 min read
Importlib package in Python
In this article, we are going to know about the Importlib package in the Python programming language. The importlib package is primarily utilized by Python applications for dynamic imports during runtime. In layman's terms, it allows the user to load modules as he/she discovers them. This package has enabled programmatic module import since Python
6 min read
How to Install a Python Package with a .whl File?
In this article, we are going to see how we can install a Python Package with a .whl file. Users must have Python 3.x (any version like 3.9,3.10 etc) installed on their device and may download any .whl file of their choice prior to following this article. The user should also need to verify that pip is already installed too. What is a wheel file? I
4 min read
How to Check If Python Package Is Installed
In this article, we are going to see how to check if Python package is installed or not. Check If Python Package is InstalledThere are various methods to check if Python is installed or not, here we are discussing some generally used methods for Check If Python Package Is Installed or not which are the following. By using Exception handlingBy using
5 min read
NetworkX : Python software package for study of complex networks
NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and function of complex networks. It is used to study large complex networks represented in form of graphs with nodes and edges. Using networkx we can load and store complex networks. We can generate many types of random and classic
3 min read
Pipenv : Python Package Management Tool
We will be exploring the Python package management tool Pipenv. It is a dependency management tool in python. It is a high-level tool for managing dependency inside a Python project Pipenv is Python's recommended package manager. It is simple and easier to use as compared to pip and virtual environment combined. Pipenv creates a virtual environment
4 min read
How to Publish Python package at PyPi using Twine module?
Python is so flexible and easy to use because of its available packages that are hosted on pypi.org, Let's see how to publish your own package on PyPi using Twine module. Requirements:You must have account of pypi.org, if don't create an accountThe twine library is created to simplify uploading packages in pypi. To install twine library.pip install
3 min read
Python | Plotting Google Map using gmplot package
gmplot is a matplotlib-like interface to generate the HTML and javascript to render all the data user would like on top of Google Maps. Command to install gmplot : pip install gmplotCode #1 : To create a Base Map [GFGTABS] Python # import gmplot package import gmplot # GoogleMapPlotter return Map object # Pass the center latitude and # center longi
2 min read
Plotting Data on Google Map using Python's pygmaps package
pygmaps is a matplotlib-like interface to generate the HTML and javascript to render all the data users would like on top of Google Maps. Command to install pygmaps : pip install pygmaps (on windows)sudo pip3 install pygmaps (on linix / unix)Code #1 : To create a Base Map. [GFGTABS] Python # import required package import pygmaps # maps method retu
3 min read
Python | Plotting Google Map using folium package
Folium is built on the data wrangling strengths of the Python ecosystem and the mapping strengths of the Leaflet.js (JavaScript) library. Simply, manipulate your data in Python, then visualize it on a leaflet map via Folium. Folium makes it easy to visualize data that's been manipulated in Python, on an interactive Leaflet map. This library has a n
2 min read
How to uninstall a package using python setup.py?
When working with Python, managing packages is a common task. Typically, package managers like pip are used for installing and uninstalling packages. However, in some cases, you might encounter packages installed via a setup.py script, particularly in development or custom environments. This guide will walk you through the steps to uninstall a pack
3 min read
Trending in News
- OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
- How to Merge Cells in Google Sheets: Step by Step Guide
- How to Lock Cells in Google Sheets : Step by Step Guide
- PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
- #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `
${comment_text}
`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `
${suggest_val}
`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `
Thank You!
Your suggestions are valuable to us.
You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.
`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });