article

Sunday, May 29, 2016

Python Package Example

Python Package Example
 
#A package is a collection of modules which have a common purpose. Technically a package is a directory which must have one special file called __init__.py
#user interface code structure
#read.py
#constants/
    # __init__.py
    #names.py

#In our current working directory we have a constants directory and a read.py script.
# __init__.py
from names import names # import names (names.py)
print "initializing constants package"

# names.py
names = ('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom')

# read.py = root directory
import constants # import constants (folder name constants)
print constants.names
#output
#initializing constants package
#('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom')

# create subpackages. To access subpackages, we use the dot operator
#read.py
#constants/
          #__init__.py
          #names.py 
          #numbers/
                   #__init__.py
                   #integers.py
#This is the new hierarchy. We have a subpackage called numbers.
#constant/numbers/__init__.py
from integers import integers

# integers.py
integers = (2, 3, 45, 6, 7, 8, 9)

# read.py
import constants
import constants.numbers as int

print constants.names
print int.integers
#output
#initializing constants package
#('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom')
#(2, 3, 45, 6, 7, 8, 9)


Related Post