Python Packages

So far we have learned about Python modules and how different functions, classes, and statements are defined inside them.

In this article, you will learn in detail about Python packages, how different modules are bundled together to create packages, how to import Python packages and many other things.

Python Package: Introduction
How to create a Python package?
How to import a Python package?
 python packages

Python Packages: Introduction

A Python package in simple words is a directory that contains Python files.

Just like a directory has sub-directories and those sub-directories also have files inside, a Python package also has sub-packages and those sub-packages again have different modules defined inside.

A directory with Python files can only be considered as Python package if the directory has a file with name __init__.py.

So every directory having a file __init__.py is considered Python package and the sub-directories having the file __init__.py are considered sub-packages.

The file __init__.py can be empty or contain code to initialize the package as it’s the first file that is executed while importing a package.

How to create a Python Package?

Creating file is like creating directories and dub-directories with a file __init__.py placed inside.

Example 1: let’s create a simple package car containing a simple module display.py.

Here is the structure for creating this package.

python package example

  1. Create a directory car to create a package of the same name.
  2. Create a file __init__.py and place it inside directory car so that it can be considered a Python package.
  3. Create a module inside directory car.The code for module display.py.
    #display.py
    def display():
    print ('This is a car.')
    

Before discussing how to import Python packages, let’s take another example and create a Python package with sub-packages.

[adsense1]

Example 2: Create a package named science containing physics, chemistry, and biology as its sub-packages.

Here is the structure.