Sunday, 5 August 2018

Python :: 13 - Package

packages



What are packages?

We don't usually store all of our files in our computer
in the same location.We use a well-organized hierarchy of
directories for easier a
ccess.


Similar files are kept in the same directory, for example, we may keep all the songs
in the "music" directory. Analogous to this, Python has packages for directories and
modules for files.

As our application program grows larger in size with a lot of modules, we place similar
modules in one package and different modules in different packages. This makes a project
(program) easy to manage and conceptually clear.Similar, as a directory can contain
sub-directories and files, a Python package can have sub-packages and modules.

A directory must contain a file named __init__.py in order for Python to consider
it as a package. This file can be left empty but we generally place the initialization
code for that package in this file.




mypackage --folder
   |
   |
   |--> __init__.py
   |--> calculations.py
   |
   |subpackage folder
|
|--> __init__.py
|-->aggregration.py
|

pkg_example.py

Here mypackage and pkg_example.py should be under same folder.

if you want to specify mypackage in golbal then copy it to site-package folder.

>>import sys
>>sys.path

calculation.py:
==============
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b

aggregration.py:
================
def sum(lst):
s = 0
for i in lst:
s = s+i
return s


pkg_example.py:
==============
import mypackage.calculation as k
import mypackage.subpackage.aggregration as l


val = k.add(10,20)
a = [10,20,30]
print("The value is ",val)

b = l.sum(a)
print("the sum of elements of list is",b)

No comments:

Post a Comment