Python Package

It is an encapsulation mechanism to group related modules into a single unit.

package is nothing but folder or directory which represents collection of Python modules.

Any folder or directory contains __init__.py file,is considered as a Python package. This file can be empty.

A package can contains sub packages also.

Here, the root package is Game. It has sub packages Sound, Image, and Level, and file __init__.py. Sound further has modules load, play, and pause, apart from file __init__.py. Image has modules open, change, and close, apart from __init__.py. Finally, Level has modules start, load, and over, apart from __init__.py.

Import Modules from Packages in Python

A Python package may contain several modules. To import one of these into your program, you must use the dot operator(.)

In the above example, if you want to import the load module from subpackage sound, we type the following at the top of our Python file:

import Game.Sound.load

Note that we don’t type the extension, because that isn’t what we refer to the module as. The subpackage Level has a module named load too, but there is no clash here. This is because we refer to the module by its fully qualified name.

To escape having to type so much every time we needed to use the module, we could also import it under an alias:

import Game.Sound.load as loadgame

(If you’re working the interpreter, you may also do the following:
loadgame=Game.Sound.load

This works equally fine.)

Alternatively, you could do:

from Game.Sound import load

Now, if the Sound subpackage has a function volume_up(), we call it this way:
loadgame.volume_up(7)

If we imported this way:

from Game.Sound.load import volume_up() as volup

We could call the function simply, without needing to use a full qualifier:
volup(7)

But this isn’t recommended, as this may cause names in a namespace to clash.

When you import a package, only the modules directly under it are imported. An import does not import the sub packages.

>>> import one
>>> one.two

File “<pyshell#488>”, line 1, in <module>

one.two.evenodd

AttributeError: module ‘one’ has no attribute ‘two’

Also note that if you want to check where your Python packages are being created, your path will look something like this:

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\Lib\site-packages

Create Your Own Python Package

Now, on to the most interesting part. Like we said, Python packages are nothing but a dictionary with sub-packages and modules, and an __init__.py file.
In our example, this is the hierarchy we create:

def check():
a=int(input(‘Enter a number’))
if a%2==0: print(“Even”)
else: print(“Odd”)

Also, we keep each init.py empty.

Now, we import and use it this way:

>>> from one.two.evenodd import check as check
>>> check()

Enter a number7
Odd

>>> check()

Enter a number0
Even

Follow Us On