Chapter: Problem Solving and Python Programming : Files, Modules, Packages

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Package - Python

A package is a collection of modules. A Python package can have sub-packages and modules.

PACKAGE

 

package is a collection of modules. 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.

Here is an example. Suppose we are developing a game, one possible organization of packages and modules could be as shown in the figure below.

   


 

Importing module from a package

 

We can import modules from packages using the dot (.) operator.

For example, if want to import the start module in the above example, it is done as follows. import Game.Level.start

Now if this module contains a function named select_difficulty(), we must use the full name to reference it.

Game.Level.start.select_difficulty(2)

 

If this construct seems lengthy, we can import the module without the package prefix as follows.

from Game.Level import start

 

We can now call the function simply as follows.

start.select_difficulty(2)

 

Yet another way of importing just the required function (or class or variable) form a module within a package would be as follows.

from Game.Level.start import select_difficulty

 

Now we can directly call this function.

select_difficulty(2)

 

Although easier, this method is not recommended. Using the full namespace avoids confusion and prevents two same identifier names from colliding.

While importing packages, Python looks in the list of directories defined in sys.path, similar as for module search path.


ILLUSTRATION PROGRAM

 

1. Word Count

 

import sys

file=open("/Python27/note.txt","r+")

wordcount={}

for word in file.read().split():

if word not in wordcount:

wordcount[word] = 1

else:

wordcount[word] += 1

file.close();

print ("%-30s %s " %('Words in the File' , 'Count'))

for key in wordcount.keys():

print ("%-30s %d " %(key , wordcount[key]))


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.