Python Package

What is a python package?

A python package is a collection of modules (A module is a file containing Python code in run time for a user-specific code, A module may contain several classes, functions, variables, etc.) Modules that are related to each other are mainly put in the same package. These packages are known as python packages.

A Python package contains several related modules. Or in other words, a python package is a hierarchical folder that contains various modules as files. As shown in the image given below.

A package is a directory of Python modules that contains an additional __init__.py file, which distinguishes a package from a directory that is supposed to contain multiple Python scripts. Packages can be nested to multiple depths if each corresponding directory contains its own __init__.py file.

__init__.py helps the Python interpreter recognize the folder as a package without this the interpreter will treat our package as a normal folder. If the __init__.py is empty then the interpreter will import all the modules of that package.

How to create our own package?

To create our own package the primary step is to give it a name through which we will access it.

Let’s create a package with the name tuf_pkg that will contain two modules module1 and module2. To create this module follow the below steps –

  1. Create a folder named tuf_pkg (Name it as per your choice).
  2. Inside this folder create an empty Python file with the name (  __init__.py )
  3. Then create two modules module1 and module2 in this folder with extension (.py) as it is a python file.

module1.py

Code:

Python Code

def tuf():
    print("Welcome to takeUforward")

module2.py

Code:

Python Code

def add():
    print(2+3)

The hierarchy of our package

Importing our package into the program –

Code:

Python Code

from tuf_pkg import module1
from tuf_pkg import module2

module1.tuf()
module2.add()

Output:

Welcome to takeUforward

5

Special thanks to Abhishek Yadav for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article. If you want to suggest any improvement/correction in this article please mail us at [email protected]