Introduction to Python Package

  • A Collection of related Modules into a single unit is nothing but a Package.
  • A package is an encapsulation(grouping) mechanism to group related modules into a single unit.
  • A python package may be a folder or A Directory
  • A python package must contain a file named as __init__.py then only python virtual machine will consider this folder as a python package folder incases of python 2x versions.
  • From python 3.3 onwards the __init__.py file is optional.
  • In python, A package may also contain sub-packages.

Variables and Data types in Python

The Advantages of Python Packages

Python provides some of the advantages of using python packages:

  • Naming conflicts can be solved easily.
  • We can identify our components uniquely.
  • Improves the Modularity of the application.
  • The readability of the application will be improved.
  • Maintainability of the application will be improved.

The following example demonstrates the use of python packages

The requirement is :

Consider my working contains a module called test.py and this module contains some packages and within that packages, and this pack contains a file __init__.py and module1.py file and inside this module1.py I want to define a function, and I want to access these function from test.py module.

So you are going to learn how to create a package and how to define modules inside a package and also learn how to access package-module functionality from test.py.

Step1 : I am going to create a pack1 folder in my current working directory called python codes

creating-a-pack1-folder-inside-pythoncodes

Step2 : And, this pack1 folder should contain two files such as __init__.py and module1.py, so goto python IDLE and select a new file and save an empty file in the pack1 folder.

creating-init-file-inside-pack1

Step3 : Now, create one more file with the below code and save inside the pack1 folder as module1.py

def function1():
    print("This is an F1 function present in module1 of pack1 package")

creating-module1-py-file-inside-pack1

Step4 : If you open a pack1 folder, you can see two files inside it.

files-inside-pack1

Step5 : create a test.py module and import module1 functionality function1()

from pack1.module1 import function1
function1()

Step6 : Run test.py module in the command prompt and the output is:

executing-test

We know that the __init__.py file is not mandatory for 3.x versions of python, so let us remove that file from the packe1 folder and execute this program again.

after-deleting-init-file

Now, if we run the test.py module, we will get the exact output as above.

executing-test-py-file-again

The following example demonstrates the package containing sub-packages.

The requirement is :

A python package called com.py internally contains two files namely, __init__.py and module1.py and this module1 contain a function1 and also the com package contains a subpackage called alert , the alert package internally contains two files namely, __init__.py nad module2.py and this module2 contain function function2

We want to access these function1 and function2 from the testt.py module.

Step1 : Let me create com package inside my current folder called python codes

creating-com-package-inside-python-codes

Step2: Create alert a sub-package inside com package

creating-alert-sub-package-inside-com

Step3: create __init__.py file inside alert as well inside the com folder

creating-init-file-inside-com-package

Now, you can see the com package contain __init__.py file and a sub-package also

com-package-contain-init-file-and-alert-sub-package

Copy and paste __init__.py file inside the alert package also

altert-package-contain-init-file

Step4: create module1.py a file inside the com package

def function1():
    print("This is the function1 of module1 present in com pacakge")

creating-module1-inside-com-package

Step5 : Create a module2.py a file inside the alert package.

creating-module2-inside-alert-package

If you want to see the folder structure of this program, go to your current folder and pass the command as treef.

folder-path-of-the-program

Step6: access the function1() and function2() from the testt.py

from com.module1 import function1
from com.alert.module2 import function2
function1()
function2()

The output is:

accessing-function1-and-function2-from-testt

Python Constructor

The Importance of __init__.py File in Python Package

The following are the importance of __init__.py file are:

  • At the time of using the package if we want to perform any activity automatically, then we have to define that activity inside this __init__.py file.
  • The __init__.py file is meant for initialization activity.

The following example demonstrates the importance of __init__.py file

The com package contains an empty __init__.py file if we execute the testt.py by importing the module1.py, the function1() will execute.

from com.module1 import function1
function1()

The output is:

importing-function1-from-testt

Now write some statements inside the __init__.py file of com package and when we execute the testt.py then this statement should be executed automatically.

print('#'*40)
print("Welcome to com package.....")
print("It provides beatiful utilities to simplify your life")
print("Just enjoy..!!!")
print('#'*50)  

The output is:

accessing-init-file

Python Bytes and Bytearray

A Relationship Between Function, Package, Module, and Library in Python Package

  • A function contains a group of repeatedly required lines of codes.
  • A Module contains a group of repeatedly required functions(including variables and classes also).
  • A Package contains a group of related Modules(Including sub-packages also).
  • A Library contains a group of related Packages.
Purpose of Installing Package:

Let us consider the following example:

My current working directory python codes contain a folder by name mypatternapp and this folder internally contains pattern package andtest.py file.

Next, the pattern package contains __init__.py and shapes.py files.

Let us create mypattern folder inside python codes

creating-mypatternapp-inside-python-codes

Now, create a pattern package inside the mypattern folder

creating-pattern-package-inside-mypatternapp

Creating an __init__.py file inside the pattern package

creating-init-file-inside-pattern-package

And also creating shapes.py module inside the pattern package.

creating-shapes-module-inside-pattern-package

Write a program inside the shapes.py module

def square():
    print("you choosed to print SQUARE pattern..")
    n=int(input("Enter No of Rows:"))
    for i in range(n):
        print('*'*n)

def right_angle_traingle():
    print("You choosed to print Right Angled Triangle pattern...")
    n=int(input("Enter No of Rows:"))
    for i in range(n):
        for j in range(i+1):
            print('*',end=' ')
        print()

def pyramid():
      print("You Choosed to print Piramid pattern..")
      n=int(input("Enter No of Rows:"))
      for i in range(n):
          print((' '*(n-i-1))+('*')*(i+1))


def diamond():
    print("You Choosedto print Diamond pattern...")
    n=int(input("Enter n values:"))
    for i in range(n):
        print(' '*(n-i-1)+'*'*(i+1))
    for i in range(n-1):
        print(' '*(i+1)+'*'*(n-i-1))

And enter some codes inside __init__.py

print('#'*70)
print('Welcome to chercher Patterns..")
print("ust call square, right_angle_triangle,pyramid,diamond functions to print shapes..")
print('#'*70)   

Let us take a test.py inside the mypatternapp folder and import shapes functions

print('#'*70)
print("Welcome to chercher Patterns..")
print("ust call square, right_angle_triangle,pyramid,diamond functions to print shapes..")
print('#'*70) 

Now go to mypatternapp and see the tree path of the program

tree-path-of-project

Now import pattern.shapes from test.py and make sure that pattern package and test.py files should be present at the same location.

creating-test-file-inside-mypatternapp

from pattern.shapes import *
square()

The output is:

square-pattern

If I wanted to print the pyramid patterns then

from pattern.shapes import *
pyramid()

The output is:

pyramid-pattern

Let us cut and paste test.py into the current working directory python codes and try to execute the program once again, then we will get an error showing module not found.

module-not-found-error

From this program, it is concluded that if we want to access python pattern into any other module, then we have to access only from the current working directory only, and hence, it is better to install python package to make it available throughout our system.

Command Line Arguments

Installation of Python Package

The Steps to install a Python package:

  • We have to write a setup.py file, which is also known as a setup script and save this setup.py file in the location where the pattern package is available in your system.
  • We have to use setup() function from setuptools module

Now write code inside the setup.py file

from setuptools import setup
set(name="pattern",
    version="0.1",
    packages=["pattern"]
    )​

creating-a-setup-file-in-mypatternapp

If you want to see the folder structure then goto mypatternapp and open a command prompt and pass the command as tree /f

path-structure-of-setup

Now, to install the package, pass the command as pip install . in the command prompt, when we call like this then setup script will be executed, and this script will execute the setup() function and this setup() function is responsible to install pattern.

installing-python-packages1 The pattern package is now installed successfully, and you can access it anywhere through your system. Goto python codes and try to execute the test.py

after-installing-pytho-pattern-executing-test-py

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions