Monday, April 20, 2020

Python Packages

What are Packages:

A package is a hierarchical file directory structure that defines a single Python application

environment that consists of modules and subpackages and sub-subpackages, and so on.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name Employee.Manager designates a submodule named Manager in a package named Employee.



Lets understand this with simple testcase.

















In the above diagram Employee here is a Package, and manager.py, softwareengineer.py and tester.py are modules.


On the development machine, it should look like as shown below.




Create a __init__.py file in the package folder.

Import the modules in the __init__.py file as shown below.


import employee.manager
import employee.softwareengineer
import employee.testers

Now in the clientscript.py file import the modules.


from employee import manager
from employee import softwareengineer
from employee import testers

After importing the modules you should be able to call the modules' functions , here m1 in manager module.


from employee import manager
from employee import softwareengineer
from employee import testers
print(manager.m1())
print(softwareengineer.m1())
print(testers.m1())




























Lets take another example where there is subpackage with in the package.

In this example we moved manager module into subpackage folder.

Add the __init__.py file in the subpackage folder.

Import the module in the __init__.py file by package heirarchy.


import employee.subpackage.manager

We have to make changes in the __init__.py file of the package folder also

import employee.subpackage
import employee.softwareengineer
import employee.testers

Focus on the first import, it is importing package.subpackage

Now make the changes in the clientscript.py to import the manager module.

from employee import subpackage
from employee import softwareengineer
from employee import testers
print(subpackage.manager.m1())
print(softwareengineer.m1())
print(testers.m1())


   










If we want to import modules from the subpackage directly, then 

from employee.subpackage import manager
manager.m1()










No comments:

Post a Comment