Create and Access a Python Package
Last Updated :
15 Feb, 2018
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
# 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
# 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
# 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.
Python
from Bmw import Bmw
from Audi import Audi
from Nissan import Nissan
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:
Python
# 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.
- 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.a8
Cars.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.
Similar Reads
Add packages to Anaconda environment in Python Let's see some methods that can be used to install packages in the Anaconda environment. There are many ways one can add pre-built packages to an anaconda environment. So, let's see how to direct the path in the anaconda and install them. Add packages to the Anaconda environment using the navigator
2 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, tensor
5 min read
How To List Installed Python Packages Working on Python projects may require you to list the installed Python packages in order to manage dependencies, check for updates, or share project requirements with others. In this post, we'll look at numerous techniques for listing the Python packages that are installed on your system.List Insta
5 min read
Create and Import modules in Python In Python, a module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, can be considered as a module named GFG which can be imported with the help of import statement. However, one might get confused about the difference between modules and pac
3 min read
Packaging and Publishing Python code If you have been coding in python, even for a while, you must be familiar with the concept of 'pip' by now. It is a package management system used to install and manage software packages/libraries written in Python. Then one may ask that where are all these packages/libraries stored? It is obvious t
7 min read
Python Packages Python packages are a way to organize and structure code by grouping related modules into directories. A package is essentially a folder that contains an __init__.py file and one or more Python files (modules). This organization helps manage and reuse code effectively, especially in larger projects.
12 min read
Command Line Scripts | Python Packaging How do we execute any script in Python? $ python do_something.py $ python do_something_with_args.py gfg vibhu Probably that's how you do it. If your answer was that you just click a button on your IDE to execute your Python code, just assume you were asked specifically how you do it on command line.
4 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 ha
6 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 visualiz
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 environm
4 min read