python Package

Package

  • Structure gathering many modules in one directory physically
    • Top directory’s name is the package’s name
    • Sub directories under the Top directory become sub-package of the top package
    • Module = file, package = directory

Role of __init__.py

  • The role recognizing the directory as a package
  • For sub-packes, this file is requried(if not, that will be usual folder)

Doing import

1
import Speech
  • Speechdirectory should be one of the directories of sys.path(or PYTHONPATH environment variable)
  • Let’s say Speech/Recognition/HMM.py looks like this
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    def train():
    print "Train"
    pass

    def loadModel():
    print "LoadModel"
    pass

    def saveModel():
    print "SaveModel"
    pass

How to use specific function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# can't use. from package's name, we need dot(.) for calling the module or function
import Speech
Speech.Recognition.HMM.train()

# Proper way
import Speech.Recognition.HMM
Speech.Recognition.HMM.train()

from Speech.Recognition import HMM
HMM.train()

from Speech.Recognition.HMM import train
train()

# Taking everything from the module. It can be used without the module's name
from Speech.Recognition.HMM import *
train()
loadModel()
saveModel()
Comments